19

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

citizenslave
  • 1,408
  • 13
  • 25
user2227145
  • 203
  • 1
  • 2
  • 7
  • 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 Feb 11 '14 at 19:15
  • 1
    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 Feb 11 '14 at 19:23
  • my aim is to use some static key to access my calendar anytime, from anywhere i would start javascript code – user2227145 Feb 11 '14 at 19:28
  • Do you have your Javascript Origins configured properly in the [Google API console](https://cloud.google.com/console/)? Are you running your script from localhost or the file system? – citizenslave Feb 11 '14 at 19:29
  • 1
    thank you for response. i ll try to use localhost instead after go dip in what s hell is JS Origins :) – user2227145 Feb 11 '14 at 19:37
  • 2
    Go back to the [Google Cloud Console](https://cloud.google.com/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 Feb 11 '14 at 19:45

4 Answers4

28

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.

citizenslave
  • 1,408
  • 13
  • 25
  • 1
    Yes. im using js from file system. thx. i ll go try load from localhost – user2227145 Feb 11 '14 at 19:37
  • I Should Say it helped me lot. please deploy same html file in server. – Parthasarathy B Jun 07 '14 at 14:38
  • On localhost I still have the same error. I don't fully understand the answer here. How do you 'configure' a domain to accept authorization, and what is your client ID? The google api console doesn't work. – Kokodoko Aug 16 '14 at 13:15
  • For debugging purposes, if you have Ruby installed, just cd to the folder where the index.html file is and run `ruby -run -e httpd .` (don't miss the dot) which will start a web server accessible at `http://localhost:8080/`. – Redoman May 18 '16 at 10:57
  • It seems there's a way of making it work from the filesystem too using CORS: https://github.com/google/google-api-javascript-client/issues/46 – Redoman May 18 '16 at 10:59
0

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%

Parthasarathy B
  • 1,942
  • 1
  • 16
  • 10
0

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

mehmet riza oz
  • 541
  • 6
  • 18
0

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.

MarckK
  • 4,061
  • 1
  • 10
  • 4