I am trying to follow the sample example from Google's developer tutorial
using updated chrome (version 38.0)
But seems like the gapi.auth functions never reached to the their callbacks
Here is a code example that demonstrate it:
<!doctype html>
<html>
<head>
<title>Google API Client test</title>
</head>
<body>
here will be the use of Oauth 2.0
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
googleApiClientReady = function() {
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: 'XXX',
scope: 'https://www.googleapis.com/auth/youtube',
immediate: true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
alert('gapi.auth return successfully');
} else {
alert('gapi.auth return with error');
}
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
When I run the above html+JS file- none of the 2 optional alerts of 'HandleAuthResult' are displayed on screen at all - meaning that this function is not called back by 'gapi.auth.authorize'
Did anyone manage to use this library properly?
First of all you need to check if chrome has blocked your popup. It's because popup-opening code is not in on-click handler.
Then you should open chrome's developer console and check "Console" tab for errors.
Also you should specify your domain name and port where your page is located in Google Developer Console like this:
I was able to login into google and receive successful callback
using your code but only after removing "immediate: true" option.
I dont know why but i was getting "immediate_failed" error.
Related
Regards,
I have found several questions regarding this error :
"ScriptError: Authorisation is required to perform that action." but I can't find one that is about my issue.
What I am trying to do is call a function .gs file from .html file using google.script.run where both of the file is in Library. Referring to this answer, this answer and this bug report, I have created the "wrapper function" in the script that is using the library, but still failed to finish the execution.
Here's what I did :
.html in Library :
<html>
<head>
<script>
function onFailure(error) {
console.log("ERROR: " + error);
}
function myfunc() {
console.log("HERE");
google.script.run.withFailureHandler(onFailure).callLibraryFunction('LibraryName.test', ['test123']);
}
</script>
</head>
<body>
<button onclick="myfunc()">CLICK</button>
</body>
</html>
.gs in Library
function test(x){
Logger.log(x);
}
.gs in script that is using the Library:
function callLibraryFunction(func, args) {
var arr = func.split(".");
var libName = arr[0];
var libFunc = arr[1];
args = args || [];
return this[libName][libFunc].apply(this, args);
}
The console logs HERE but then it logs ERROR: ScriptError: Authorisation is required to perform that action. instead of the expected output, test123.
NOTE: The HTML is for custom modeless dialog box in Sheets and not for Web App.
I really hope someone can help me in this. Thank you in advance.
You need to grant access of the library "LibraryName" as an authorized app in your Gmail account the same way how you grant access to the calling script. I guess you have called the method HtmlService.createHtmlOutputFromFile(...) in your library. This requires more authorization. You need to grant this. What you can do is create a temporary function in the library that has HtmlService.createHtmlOutputFromFile(..). Run it from the script editor and the authorization requirement window appears. Proceed in granting access...
I'm currently using the LinkedIn JS SDK as documented here for my AngularJS application. I'm inserting the following script into the head block of my page:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [apiKey]
authorize: false
</script>
Then I initiate authorization with an onclick function on a button like so
IN.User.authorize(function(){
callback();
});
At this point the user is authenticated with LinkedIn and I can use LinkedIn's APIs.
When the user decides to log out, I use the call IN.User.logout() to end the user's session. However, the call causes this error 'Uncaught Error: no XD object is available from this page' to appear in the JavaScript console.
This only happen sometimes, and I'm unsure of why this exact issue occurs. Most of the time, the SDK will logout the session normally. I make sure that the LinkedIn framework is loaded before calling any functions and I call IN.User.isAuthorized() before making a call to logout. Does anyone have an idea of what I may be doing wrong?
if (IN.User.isAuthorized()) { // Returns true
IN.User.logout(); // Prints `'Uncaught Error: no XD object is available from this page' error
}
EDIT:
I'm looking more into the source code and it shows this function being called:
Sslac.Function("IN.Support.getXD", function() {
function a() {
throw Error("no XD object is available from this page");
}
try {
return IN.Support.isSingleJS() && IN.Support.isPopup() ? IN.Support.generateXDProxy() : IN.Support.isPopup() ? window.opener.getXD || a : IN.Support.isIframe() ? window.parent.getXD || a : a
} catch (b) {
return a
}
}());
But the IN.Support object is null which is why this error is being thrown. Could anyone from LinkedIn help with this? It looks like there's some kind of race condition.
I could not fix the 'no XD object is available from this page' error. As a workaround, I called the logout URL itself to end the user session. This still causes the error to appear in the console but the logout function fully completes this way.
I am a "newbie" to the Google Analytics API and I am trying to get the "Hello Analytics" example working.
I followed their steps
to create the test web page but I got no results.
When I go to my web page, I see the title, the "Sign in" button and the text area below where the result should appear. When I press "Sign in", that seems to work; the button changes to say "Signed In". However, no results appear.
I am using FireFox so I right-clicked on the text area and selected "Inspect Element"; this shows this error message:
Object { result: Object, body: "{ "error": { "code": 403, …",
headers: Object, status: 403, statusText: "Forbidden" }
I think this is a permission error but do not know how to correct it.
Here is my file HelloAnalytics.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics Reporting API V4</title>
<meta name="google-signin-client_id" content="959582115031-ardmn5vsir7kbcp0dme4d4n1p45bd649.apps.googleusercontent.com">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<h1>Hello Analytics Reporting API V4</h1>
<p>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<div class="g-signin2" data-onsuccess="queryReports"></div>
</p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Replace with your view ID.
var VIEW_ID = '92320289';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
metrics: [
{
expression: 'ga:sessions'
}
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>
I need to understand how to use the Google Analytics API to do simple queries.
FINALLY got it to work!
I was trying to use the API to get data for the Google sample site ("Google Merchandise Store"). I was trying to think of possible reasons for the permission error, and it occurred to me that maybe Google didn't allow Analytics API calls for that web site.
So I went through the effort of setting up my own test web site with Google's Javascript tracking code in it, then defining a new project, enabling the API for it, creating credentials (a client ID) and getting the view ID for my web site. With the new client ID and view ID in my HelloAnalytics.html page, it worked perfectly.
So my guess was correct: Google does NOT permit API calls to get data for its "Google Merchandise Store" sample website. They REALLY should mention this on their "quickstart" page because a "newbie" (like me) wouldn't know that!
I thought I should post my solution because I'm sure that somebody else will run into this problem in the future.
FYI- I have HelloAnalytics.html running on a web server. I am using free web space provided by my ISP.
I'm developing an app for iOS with Phonegap and I'm using parse.com for push notification with iOS SDK included with Xcode. In my app users can login and I need to know the device token of the users to send to them single push notification, I know how to send the device token with the user/password during log in but I don't know how to read it, I don't know if there is any way directly with Phonegap or if I need to read it with C and then pass to Javascript with a variable.
EDIT: I'm trying to use Malloc's solution, and i have this problem. i installed plugin via CLI but i don't understand how to use it. I create a sample page
<html>
<head>
</head>
<body>
<script type="text/javascript> parsePlugin.getInstallationId(function(id) { document.write(id); }, function(e) { alert('error'); });
</script>
</body>
</html>
but of course i obtain a white page because this code don't print anything.
What i need to do if i want to assign installationid to a javascript variable?
thanks
UPDATE 2
Now I have this code in my sample page
<html>
<head>
</head>
<body>
<script type="text/javascript">
var appId = p3Z10Nj2GdmfuxCX1a9liu5VlPadbvgW********;
var clientKey = lFRl93OEDM0bFTVOKaA1iIXV4vuWS3S9********;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
</script>
</body>
</html>
UPDATE 3
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(window).load(function() {
var appId = p3Z10Nj2gm8siK;
var clientKey = lFRl93OEDM0bFTVOKaA1iIXV4vu;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
}
</script>
</body>
</html>
What you need is the device related installation id. You may need to use a plugin for this.
The plugin I have used, and which worked as expected, can be found here.
After installing it with the CLI, you just call the parsePlugin.getInstallationId function which will return the installation id for your device.
Keep in mind that you will get ONE installation id per device but that doesn't mean that you have always only one. Since you may run the app on more than a device, each one has his installation id.
Update:
The plugin should be initialized before calling getInstallationId:
$(window).load(function() {
var appId = YOUR_APP_ID;
var clientKey = YOUR_KEY_CLIENT;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
}
You should be using a plugin as others pointed out, here is another plugin that does the same job.
https://github.com/ccsoft/cordova-parse
PS: I am the author of the plugin.
I need to use Twitter's Search API. I read twitter's developer documentation and it says that client side authentication is not recommended anymore. But, since mine is really a small application and on a very tight deadline, I decided to use codebird-js.
Here is my code:
<script type="text/javascript" src="sha1.js"></script>
<script type="text/javascript" src="codebird.js"></script>
<script type="text/javascript">
function loginTwitter() {
var cb = new Codebird();
cb.setConsumerKey("my_consumer_key","my_consumer_secret");
cb.setToken("my_token", "my_token_secret");
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
alert("hey");
},
true
);
}
</script>
Dont think there is any problem with the callback of search tweets, since this is what is documented in codebird-js.Kindly suggest any alternatives to make the code work.
Also, I enabled the option "Allow application to sign in with twitter" in application settings.
You have to make some syntax corrections to your code and to call the "loginTwitter()" function; the code should be:
<script type="text/javascript" src="sha1.js"></script>
<script type="text/javascript" src="codebird.js"></script>
<script type="text/javascript">
function loginTwitter() {
var cb = new Codebird();
cb.setConsumerKey("my_consumer_key", "my_consumer_secret");
cb.setToken("my_token", "my_token_secret");
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
alert(JSON.stringify(reply)); //do something with the result
},
true
);
};
loginTwitter();
</script>
And don't forget to download the codebird for javascript and put its files into the same folder as your main file (according to the path that you have put in your script).