Вопрос

I have the following code, which is supposed to be a simple example of using the google api javascript client, and simply displays the long-form URL for a hard-coded shortened URL:

<script>
  function appendResults(text) {
    var results = document.getElementById('results');
    results.appendChild(document.createElement('P'));
    results.appendChild(document.createTextNode(text));
  }

  function makeRequest() {

    console.log('Inside makeRequest');

    var request = gapi.client.urlshortener.url.get({
      'shortUrl': 'http://goo.gl/fbsS'
    });

    request.execute(function(response) {
      appendResults(response.longUrl);
    });
  }

  function load() {

    gapi.client.setApiKey('API_KEY');
    console.log('After attempting to set API key');
    gapi.client.load('urlshortener', 'v1', makeRequest);
    console.log('After attempting to load urlshortener');
  }
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>

except with an actual API key instead of the text 'API_KEY'.

The console output is simply:

After attempting to set API key

After attempting to load urlshortener

but I never see 'Inside makeRequest', which is inside the makeRequest function, which is the callback function for the call to gapi.client.load, leading me to believe that the function is not working (or failing to complete).

Can anyone shed some light on why this might be so and how to fix it?

Thanks in advance.

Это было полезно?

Решение

After spending hours googling the problem, I found out the problem was because I was running this file on the local machine and not on a server.

When you run the above code on chrome you get this error in the developer console "Unable to post message to file://. Recipient has origin null."

For some reason the javascript loads only when running on a actual server or something like XAMPP or WAMP.

If there is any expert who can shed some light to why this happens, it would be really great full to learn.

Hope this helps the others noobies like me out there :D

Другие советы

Short answer (http://code.google.com/p/google-api-javascript-client/issues/detail?id=46):

The JS Client does not currently support making requests from a file:// origin.

Long answer (http://en.wikipedia.org/wiki/Same_origin_policy):

The behavior of same-origin checks and related mechanisms is not well-defined
in a number of corner cases, such as for protocols that do not have a clearly 
defined host name or port associated with their URLs (file:, data:, etc.). 

This historically caused a fair number of security problems, such as the 
generally undesirable ability of any locally stored HTML file to access all 
other files on the disk, or communicate with any site on the Internet.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top