19
votes

I am trying to get calendar info from google in javascript. I ve read 'how to' manuals. They didn't help. Even this 'helpful' copypasted code (to authorize) didn't. Would somebody be so kind to teach me how to use google api? Maybe someone has some samples to share

And this beautiful js code :

<html>
<button id="authorize-button" onclick='handleAuthClick()'>Authorize</button>

<script type="text/javascript">
    var clientId = '***';
    var apiKey = '***';
    var scopes = 'https://www.googleapis.com/auth/plus.me';

    function handleClientLoad() {
        gapi.client.setApiKey(apiKey);
        window.setTimeout(checkAuth,1);
    }

    function checkAuth() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
    }

    function handleAuthResult(authResult) {
        var authorizeButton = document.getElementById('authorize-button');
        if (authResult && !authResult.error) {
            authorizeButton.style.visibility = 'hidden';
            makeApiCall();
        } else {
            authorizeButton.style.visibility = '';
            authorizeButton.onclick = handleAuthClick;
        }
    }

    function handleAuthClick(event) {
        // Step 3: get authorization to use private data
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        return false;
    }

    // Load the API and make an API call.  Display the results on the screen.
    function makeApiCall() {
        // Step 4: Load the Google+ API
        gapi.client.load('plus', 'v1', function() {
            // Step 5: Assemble the API request
            var request = gapi.client.plus.people.get({
            'userId': 'me'
            });
            // Step 6: Execute the API request
            request.execute(function(resp) {
            var heading = document.createElement('h4');
            var image = document.createElement('img');
            image.src = resp.image.url;
            heading.appendChild(image);
            heading.appendChild(document.createTextNode(resp.displayName));

            document.getElementById('content').appendChild(heading);
            });
        });
    }
</script>

Error Message (from Console):

 'Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').'

so im stuck on 'gapi.auth.authorize'. nothing works after

4
That doesn't look exactly like the code I'm using, but I've gotten the GAPI JS client to authenticate and query from inside an AngularJS service so I wouldn't expect it to. What's the exact issue you're having? How far along do you get? Is the GAPI loading? Are you getting the popup demanding authentication and authorization? If you console.log your authResult, is it populated? What if you console.log the resp in the execute callback? Have you blocked the Google Login popup? - citizenslave
in console im getting 'Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').' so im stuck on 'gapi.auth.authorize'. nothing works after that line. - user2227145
my aim is to use some static key to access my calendar anytime, from anywhere i would start javascript code - user2227145
thank you for response. i ll try to use localhost instead after go dip in what s hell is JS Origins :) - user2227145
Go back to the Google Cloud Console where you configured your project and got your Client ID. You should have to fields you can still edit for Javascript Origins and Redirect URIs. The Origins list the hosts that the GAPI server will accept authorization requests from. If http://localhost isn't in the list, then requests from http://localhost will generate an error similar to the one you're already getting from the file system, which is not supported at all. - citizenslave

4 Answers

28
votes

Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID.

0
votes

Google API Console reference :

In Client ID for web application:

Javascript Origins : http://localhost:3000/


Key for browser applications:

Referers : http://localhost:3000/

localhost would work 100%

0
votes

i got the same error and as you preferred, after running html file in my local web server problem solved.

i created credentials for web application and set following values both to my local with "http://localhost:5000" string

"Authorized JavaScript origins" 
"Authorized redirect URIs

i checked the json file too. i got the following json file as a result.

{"web":
 {
    "client_id":"myClientID",
    "project_id":"my-project",
    "auth_uri":"https://accounts.google.com/o/oauth2/auth",
    "token_uri":"https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
    "client_secret":"XqXmgQGrst4xkZ2pgJh3Omxg",
    "redirect_uris":["http://localhost:5000"],
    "javascript_origins":["http://localhost:5000"]
 }

}

https://developers.google.com/drive/v2/web/auth/web-client

0
votes

Some APIs will work fine when queried from local files, but some won't. In response to an error such as yours, try to serve your files from a web server. If you need a quick web server running, use Python's builtin HTTP server (Mac OSX and Linux systems have Python pre-installed). This HTTP server can turn any directory in your system into your web server directory. cd into your project directory and run the following command: python -m SimpleHTTPServer 3000 The number at the end is the port number your http server will start in and you can change that port number. In our example, your directory would be served from: http://localhost:3000.