简体   繁体   中英

Google URL Shortener API with Javascript

I don't receive an error, but the Javascript code just stops executing when I run the following function:

function initGoogleURL() {
    gapi.client.setApiKey(myAPIKey);
    gapi.client.load('urlshortener', 'v1').then(function(value) {
        console.log("success!");
        googleReady = true; // Success!
    }, function(reason) {
        console.log(reason); // Error!
    });
}

I don't see a message in the console. And the rest of the code stops executing, even though it's not dependent on this path of execution.

Any ideas why this is happening?

First of all - the fact that you are getting no message in the console is concerning. Are you sure you're executing the code? Do you have the line

initGoogleURL();

somewhere in your code? Assuming you do, I think the issue is similar to the one described here . My rational for this is if I set a timeout on the function, for example:

setTimeout(function(){
  initGoogleURL();
}, 5000) // Second argument is time to wait before executing the function

then, I get a success message printed out. If you see similar behavior, your issue is that you are trying to use the google api before it has been fully loaded. The resolution to this is to define a callback handler for when the API library is successfully loaded, as prescribed in your import statement in HTML, eg:

<script src="https://apis.google.com/js/client.js?onload=OnLoadCallback"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM