Google Calendar API javascript Error:Origin Mismatch - javascript

I'm working on a simple javascript code I found here: http://googleappsdeveloper.blogspot.com/2011/12/using-new-js-library-to-unlock-power-of.html
It basically acquires authentication to a google Calendar and retrieves the list of events contained in it. I have registered my web application and obtained a client ID and API Key.
I'm facing this error: "Error: Origin mismatch", I'm running the javascript locally using localhost and I set my homepage in the google application registration to localhost as well.
any help would be immensely appreciated.
the code:
<html>
<body>
<div id='content'>
<h1>Events</h1>
<ul id='events'></ul>
</div>
<a href='#' id='authorize-button' onclick='handleAuthClick();'>Login</a>
<script>
var clientId = '506979856128.apps.googleusercontent.com';
var apiKey = 'AIzaSyAGbQAZQU0YNL8hK5EU69exIg7_sOg3JoA';
var scopes = 'https://www.googleapis.com/auth/calendar';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: clientId, scope: scopes, immediate: false},
handleAuthResult);
return false;
}
function makeApiCall() {
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary'
});
request.execute(function(resp) {
for (var i = 0; i < resp.items.length; i++) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(resp.items[i].summary));
document.getElementById('events').appendChild(li);
}
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"> </script>
</body>
</html>

I got the same error origin mismatch today.after bit of search i got the reason.
While creating the Google Api Access,we have to specify Authorized Redirect URIs and Authorized Redirect URIs.
Now if you call the Login from URIs other than specified in Authorized Redirect URIs, error:Unknown Origin is thrown
FYI:I have seen that you are running the javascript locally using localhost.
It means that You have not added localhost uri to Authorized Redirect URIs.
But Don't waste your time doing that.Authorized Redirect URIs will not accept localhost uri.It's due to Chrome's same origin policy.and If you run chrome with the disable-web-security flag, it'll work locally too.

The problem of origin mismatch can be solved by taking care for Redirect URIs and Javascript Origins when creating Client ID in Google Developers Console.
The Javascript Origins should not end with /.
Example: http://example.com/ --> The correct format will be http://example.com.

Related

Synology SSO Server

I have a Synology DS212j and already set up the apache and now also SSO Server. In the SSO Server Settings I added a new Application (Name, REdirect URI). My Code now is:
<html>
<head>
<!-- include Synology SSO js -->
<script src="http://NASADRESSE:5555/webman/sso/synoSSO-1.0.0.js"></script>
</head>
<body>
<script>
function setButton (logged) {
if (logged) {
document.getElementById('button').innerHTML = '<button onclick="SYNOSSO.logout()">Logout</button>';
} else {
document.getElementById('button').innerHTML = '<button onclick="SYNOSSO.login()">Login</button>';
}
}
function authCallback(reponse) {
console.log(JSON.stringify(reponse));
if (reponse.status == 'login') {
console.log('logged');
setButton(true);
}
else {
console.log('not logged ' + reponse.status);
setButton(false);
}
}
SYNOSSO.init({
oauthserver_url: 'NASADRESSE:5555',
app_id: '9a23da153795803e0334d9873b0013dd',
redirect_uri: 'NASADDRESSE/?redirect',
callback: authCallback
});
</script>
<h1> Syno SSO test</h1>
<p id='button'></p>
</body>
</html>
NASADRESSE is correct and my Rooter redirect port 5555 to 5000. Wenn I click login, a popup window opens where I can loggin with my NAS user. But it always says its a wrong password. But I entered the right one.
Why in your script link included .ch but in your config the domain have no .ch
http://NASADRESSE.ch:5555/webman/sso/synoSSO-1.0.0.js
SYNOSSO.init({
oauthserver_url: 'NASADRESSE:5555',
app_id: '9a23da153795803e0334d9873b0013dd',
redirect_uri: 'NASADDRESSE/?redirect',
callback: authCallback
});
May it go with wrong config?
1 - install the Directory Server package, enable LDAP server
2 - configure your DSM to connect to it (Control Panel-> Domain/LDAP)
3 - connect using the LDAP users

OAuth 2.0 Authentication screen stays open

Quick question that has be baffled.
I'm following the examples from I/O '12 ( link ) and I got it working but for some reason after I grant access, the window goes to a white screen, the title says "Connecting..." and stays there. There are no errors in the console, and I'm good to go as far as the OAuth authentication is concerned.
I want to point out that I'm doing this inside a Chrome extension's popup using a page action. I don't know if that makes any difference.
The demo of that sample works great so I'm thinking it has something to do with being inside a chrome extension. I just can't figure out what it could be. demo
The code I'm using is pretty much identical to the sample:
js/oauth/oauth.js:
var clientId = '[MY_CLIENTID]';
var apiKey = '[MY_API_KEY]';
var scopes = 'https://www.googleapis.com/auth/plus.me';
// Use a button to handle authentication the first time.
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');
var flows = document.getElementById('flows');
var welcome = document.getElementById('welcome');
if (authResult && !authResult.error) {
flows.style.display = 'none';
welcome.style.display = '';
makeApiCall();
} else {
flows.style.display = '';
welcome.style.display = 'none';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
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() {
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
var heading = document.createElement('p');
var image = document.createElement('img');
image.src = resp.image.url;
var welcometext = document.createTextNode("Welcome ");
var welcometextend = document.createTextNode(", you are now logged in!");
heading.appendChild(welcometext);
heading.appendChild(document.createTextNode(resp.displayName));
heading.appendChild(welcometextend);
document.getElementById('content').appendChild(heading);
document.getElementById('avatar').appendChild(image);
});
});
}
popup.html:
<html>
<head>
<script src="js/oauth/oauth.js"></script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body style="width: 500px">
<div id="flows" style="display: none;" >
<h2>Please log in before starting</h2>
<button id="authorize-button">Log in</button>
</div>
<div id="welcome" style="display: none;">
<div id="avatar"></div>
<div id="content"></div>
</div>
</body>
</html>
sdlkfad
This is what it looks like:

Using JavaScript to get information from BigQuery

I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?
I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.
I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.
Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = '605902584318';
var client_id = '605902584318.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Update: I opened the Developer Tools in Chrome and found this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('file://') does not match the recipient window's origin
('null')
.
I tried editing in my Google Developer console as per these instructions: Google API in Javascript
Still same error.
Looks like you may need to add:
$('#query_button').show();
to the bottom of the auth() function
like so:
function auth() {
gapi.auth.authorize(config, function()
{
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
$('#query_button').show();
}
Searching for the error you got, I found this page:
Google API in Javascript
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
It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.
So I changed the code to be:
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:
python -m SimpleHTTPServer 8888
and then went to localhost:8888 in my browser and clicked my html file there.
Thanks so much for all the feedback!
It worked perfectly! Now to change the query for my purposes!

Google Calendar API Javascript Quickadd

Trying to allow a user to authenticate and quickadd an event using the Google calendar API v3 with javascript. I dont see the authenticate button. I am very inexperienced with coding.
Console:
Uncaught SyntaxError: Unexpected token } test.html:47
Uncaught TypeError: Cannot read property 'qainput' of undefined test.html:62
onload test.html:62
html file:
<html>
<head>
<meta charset='utf-8' />
<style>
#info {
border: 0px solid black;
padding: 0.25em;
margin: 0.5em 0;
}
</style>
<script type="text/javascript">
var apiKey = 'AIzaSyDcbjOvAT85hCdVrjgUAqylf_QtxE2Gx60';
var clientId = '202852486259.apps.googleusercontent.com';
var scopes = 'https://www.googleapis.com/auth/calendar';
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) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
function makeRpcRequest() {
var qatext = document.qaform.qainput.value;
var request = gapi.client.calendar.events.quick_add({
'calendarId': 'primary',
'text': +qatext+
});
request.execute(writeResponse);
}
function writeResponse(response) {
console.log(response);
var name = response.summary;
var infoDiv = document.getElementById('info');
var infoMsg = document.createElement('P');
infoMsg.appendChild(document.createTextNode(+ name' sucessfully created!'));
infoDiv.appendChild(infoMsg);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body onload="document.qaform.qainput.focus();">
<button id="authorize-button" style="visibility: hidden">Authorize to Use QuickAdd</button>
<form id="qaform">
<input placeholder='QuickAdd' name='qainput' />
<button id="rpc" onclick="makeRpcRequest();">Add</button>
</form>
<div id="info"></div>
</body>
</html>
As its been a few weeks you've probably found your answer but I was having the same issue recently starting with basically the same code that you're using. I had simply not activated google calendar under "services" in the google console. If all of the console settings aren't correct, the "authorize" button remains hidden(it is hidden by default). Once all the settings are correct and the script is communicating properly with the api, the authorize button becomes visible and you can then add the event and write the response by clicking the button.

Can I access a user's friend status using Facebook Graph API?

I am making an web app that shows the authenticated user's friends statuses. Is there anyway I can do this using Facebook's graph API? The only thing I am finding is FQL which I can't use because I am not allowed to use php.
Edit: Also I don't need alot of statuses. I only need their friends latest one.
Edit: fbID is the facebook ID. Here is my code:
<script>
var self;
(function(d){ // Load the SDK Asynchronously
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
window.fbAsyncInit = function() { // Init the SDK upon load
FB.init({
appId : '190843834372497', // App ID
channelUrl : 'http://people.rit.edu/~cds7226/536/project3/channel.html', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) { // user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
//Add rest of code here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
self=me;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else { // user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
document.getElementById('auth-loginlink').addEventListener('click', function(){ // respond to clicks on the login and logout links
FB.login(function(response){},{scope: 'friends_status,read_stream'});
});
}
</script>
Then this function executes when you click the button. It gets the User's last checked in location, and personal information including their facebook ID.
function getFriendsCheckin(token)
{
$.getJSON('https://api.foursquare.com/v2/checkins/recent?oauth_token='+token+'&v='+"20120514",function(results){
//console.log(results);
$.each(results['response']['recent'], function(key,value){
//console.log(key+' : '+value);
//Friends personal info
var fullName = value['user']['firstName']+" "+value['user']['lastName'];
var timeStamp = value['createdAt'];
var photo = value['user']['photo'];
var fbID = value['user']['contact']['facebook'];
//Where they last checked in
var locName = value['venue']['name'];
var location = new google.maps.LatLng(value['venue']['location']['lat'],value['venue']['location']['lng']);
//setMarker(location,fullName+'#'+locName);
setCustomMarker(location,fullName+'#'+locName,fbID,photo);
});
})
}
Lastly this is where the problem is. This function is suppose to show the user's friendd last status when the maker is clicked on google maps.
function setCustomMarker(location,title,fbID,icon)
{
//alert("here");
var marker = new google.maps.Marker({
position: location,
draggable: false,
map: map,
title: title,
//icon: icon
//icon: new google.maps.MarkerImage({url: icon, size: new google.maps.Size({width:10,height:10})})
});
google.maps.event.addListener(marker,'click',function(){
console.log('SELECT status_id,message FROM status WHERE uid='+fbID);
FB.api(
{
method: 'fql.query',
query: 'SELECT status_id,message FROM status WHERE uid='+fbID
},
function(response){
console.log(response);
}
);//*/
});
}
May be you are confused, but you can use fql with javascript sdk.
e.g.
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=me()'
},
function(response) {
alert('Your name is ' + response[0].name);
}
);
See reference
If you use graph api, this should work (not tested but you can check and updated me)
FB.api('/','POST',{
access_token:'<your_access_token>',
batch:[
{
"method": "GET",
"relative_url": "me/friends?limit=5",
"name": "get-friends"
},
{
"method": "GET",
"depends_on":"get-friends",
"relative_url": "{result=get-friends:$.data.*.id}/statuses"
}
]
},function(response){
console.log(response);
})
Ofcourse you need permission required for reading status updates of friends.
Try this:
FB.api('user_id/statuses','GET',{
//friends_status access token
});
Yes. It can be done with the help of graph API.
In the reference doc - take a look at the profile feed API call. There in that sample replace me with the user-id of the friend whose feed you are trying to access.
However, to do so via an app, you need to ask for read_stream and friends_status permissions from the user who is trying to use your app.
From my experience using client side Facebook js-sdk to handle OAuth is the easiest thing to do.
For the apps hosted on heroku, they provide sample implementation of client side OAuth handling and that is very useful. (To be able to host your app on heroku - while creating your app in developers.facebook.com/apps just make sure to choose "Host the project on Heroku" option.

Categories

Resources