Uncaught ReferenceError: init is not defined - javascript

im a newbie in javascript and wanted to learn something, I've been wondering, i found this on https://developers.google.com/api-client-library/javascript/features/cors where i can use cors so i can access a google API like kissflow, i dont know if im in the right way. so here's the thing, im using the standalone Auth client that was described in the said site, but everytime i tried to run the program the error prompt
Uncaught ReferenceError: init is not defined
i just copied the code at the site which is
<script src="https://apis.google.com/js/api.js"
type="text/javascript">
</script>`<script type="text/javascript">`
//<![CDATA[gapi.load('auth', init);//]]>
</script>

Try this:
<script src="https://apis.google.com/js/api.js"
type="text/javascript">
</script>
<script>
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "<YOUR_CLIENT_ID>"});
});
</script>
Make sure that you host this locally, and when creating the client ID, add the localhost URL with the port. Without a URL, the client ID will not send back a proper response, resulting in an error. Since the client ID doesn't support "file:///", you have to use a web hosting service or something, or the easier route, just download the latest python and set up a localhost server.
Latest python download: https://www.python.org/downloads/
Setting up the server: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server#running_a_simple_local_http_server
Note that sometimes you have to use "py" instead of "python" for reasons I am too lazy to research 😊.
To actually initiate the login and use the API:
<script>
function authenticate() {
return gapi.auth2.getAuthInstance().signIn({scope: ""/*Declare scopes with spaces in between, depends on API you're using*/})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("<YOUR_API_KEY>");
return gapi.client.load(""/*Declare discovery document, depends on API you're using*/)
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
function execute() {
return gapi.client.classroom.courses.list({}) //Used classroom courses list as an example, but use the apropriate API Fields, found in your method's "Overview" section on the API Documentation
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "<YOUR_CLIENT_ID>"});
});
authenticate().then(loadClient).then(execute)
</script>
Note that sometimes you have to clear cache in order for this to work (I mean, worked for me), so if you have some trouble, try that.

Related

Meteor reports my server method does not exist

fairly new to Meteor and JS, doing a lot of reading and research. I have been following an example of an HTTP request but I keep getting an error "404, method Abc not found":
This is how my JS file looks like:
if (Meteor.isServer) {
Meteor.methods({
Abc: function () {
this.unblock();
return Meteor.http.call("GET", //HTTP REQUEST TEXT);
}
});
}
if (Meteor.isClient) {
Meteor.call("Abc", function(error, results) {
console.log(error);
console.log(results);
});
}
Why the server method is not found if it is in the same file? I only want to show the content of the HTTP response.
Debugging and re-reading the tutorials.
Apparently, your code is loaded only on the client side. You should separate the client and the server logic by using the "client" and "server" folders respectively . Or in your example you should use "both" folder.

Getting stream permissions from the user in the Oauth login

I am new to the Google api and I am working on an app to allow us to stream a video to a user's youtube account. I'm having a hard time determining how to configure the login process to handle that. I used the sample code from the SDK and the login window opens fine. But I can't determine what is the scope and discovery docs to pass in the enable the Live Streaming API. Any help would be greatly appreciated.
Edited to add: I found the code snippet below and it now loads the window prompting me to give permission. But when I click to allow the app access it returns calls the error function with the message "popup_closed_by_user"
gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube"})
.then(function() {
try {
console.log("Sign-in successful");
gapi.client.setApiKey(global.google_stream_apiid);
var tmp2 = gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() {
console.log("GAPI client loaded for API");
},
function(err) {
console.error("Error loading GAPI client for API", err);
});
console.log(tmp2)
}
catch(e){
Ext.ux.Error.handleError(e);
}
},
function(err) {
debugger;
console.error("Error signing in", err);
});

Copied example from documentation of Youtube API not working

I'm trying to search for a video with some words using Youtube API and I have run my example on this interactive app https://developers.google.com/youtube/v3/docs/search/list?apix=true&apix_params=%7B%22part%22%3A%5B%22snippet%22%5D%2C%22q%22%3A%22ay%20vamos%22%7D. I have copied the source code on that page and removed authorization because I don't need it and filled credentials. This is the error I keep on getting Uncaught TypeError: Cannot read property 'youtube' of undefined
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for youtube.search.list
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function loadClient() {
gapi.client.setApiKey("-------------------");
return gapi.client
.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(
function () {
return gapi.client.youtube.search
.list({
part: ["snippet"],
q: "ay vamos",
})
.then(
function (response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function (err) {
console.error("Execute error", err);
}
);
},
function (err) {
console.error("Error loading GAPI client for API", err);
}
);
}
// Make sure the client is loaded and sign-in is complete before calling this method.
</script>
<button onclick="loadClient()">execute</button>
</body>
"Cannot read propery 'youtube' of undefined" hints that gapi.client isn't defined properly. I ran your code myself and printing gapi.client to the console outputs null.
Also, I couldn't find anything that is calling your loadClient() function which looks like it is responsible for actually loading the youtube client? That could be a separate issue.

Using the Google API javascript in Cordova / Phonegap

I'm developing an application with Cordova and would like to save files in Googe Drive.
I've got success in login to Google, using the cordova-plugin-googleplus (https://github.com/EddyVerbruggen/cordova-plugin-googleplus). However I could not get the plugin returns to me accessToken or idToken so I could use with Google javascript API.
window.plugins.googleplus.login(
{
'scopes': 'https://www.googleapis.com/auth/drive.file profile',
'offline': true,
'webApiKey': ‘CODE’
},
function (obj) {
$scope.$apply(function() {
$scope.srcImage = obj.imageUrl;
$scope.NomeGoogle = obj.displayName;
});
},
function (msg) {
alert('Erro');
alert('error: ' + msg);
}
);
I tried using the code below, but returned me the following error:
"Uncaught gapi.auth2.ExternallyVisibleError: Invalid cookiePolicy"
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'REVERSED_CLIENTID',
}).then(function(){
auth2 = gapi.auth2.getAuthInstance();
console.log(auth2.isSignedIn.get()); //now this always returns correctly
});
});
I managed to figure out the problem, why wasn´t getting the serverAuthCode from plugin.
It is necessary to create 2 credentials on the Google Developers Console. The 1st must be Android, this will be for the plugin and the 2nd should be a Web App, this is necessary to achieve serverAuthCode.
The code looks like this
window.plugins.googleplus.login(
{
'scopes': 'https://www.googleapis.com/auth/drive.file profile',
'offline': true,
'webApiKey': ‘REVERSED_CODE of Web App Credential’
},
function (obj) {
$scope.$apply(function() {
$scope.srcImage = obj.imageUrl;
$scope.NomeGoogle = obj.displayName;
});
var data = $.param({
client_id: 'REVERSED_CODE of Web App Credential',
client_secret: 'SECRET_CODE of Web App Credential',
grant_type: 'authorization_code',
code: obj.serverAuthCode
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post("https://www.googleapis.com/oauth2/v3/token", data, config).success(function(data, status) {
//data.access_token;
/** from now you can do use of google API **/
})
.error(function(data, status) {
console.log(data);
console.log(status);
});
},
function (msg) {
alert('Erro');
alert('error: ' + msg);
}
);
Thank you for your reply rojobo
At first I was hoping to skip the need for cordova-plugin-googleplus and just use the gapi within Cordova/PhoneGap to handle authentication with Google, but it appears the gapi client authentication may not work within cordova's file:// protocol.
The answer from #Joao sent me in the right direction, but I kept getting the Invalid cookiePolicy error when trying to use the gapi after retrieving the access_token (this was because I was ignoring step #2 listed below, and after authenticating with the plugini I was mistakenly trying to authenticate again with the gapi).
There is a step (#3 mentioned below) that was unclear to me. To authenticate with Google and then use the gapi in Cordova/PhoneGap, this worked instead...
use the cordova-plugin-googleplus to take care of the authentication and access token retrieval, do not use the gapi at all here
load the gapi client library (skip over the gapi.client.init() call and all the normal gapi authentication procedures)
Attach the access token we got from the plugin to the gapi client, and then make your gapi calls as needed
Step #3 took some digging for me to find, and meant I needed to add the access_token
gapi.client.setToken({access_token:'abc123456xyz'});
Once the access token was attached to the gapi client, I could use the gapi within Cordova/Phonegap:
// Load the YouTube API.
gapi.client.load('youtube', 'v3', function() {
// Do stuff...
};
try
window.plugins.googleplus.login(
{
'scopes': 'https://www.googleapis.com/auth/drive.file profile',
'offline': true,
'cookiepolicy': 'none',
'webApiKey': ‘CODE’
}

OAuth.io connection failed

I'm new to web programming and I try to use oauth.io in my web-app. I finished configurations to facebook and Google due to the instruction. Everything works fine when i tested the configuration from their site. However when i tried to implemented to my webapp, OAuth won't connect to the provider.
I loaded the oauth.js in html, created a button in html and use onclick="pop" to invoke the function in javascript. And within the pop() function in javascript I've added:
OAuth.initialize('the-public-key-in-my-acc");
OAuth.popup('facebook', function(err, res) { if (err) { alert(something)});
Then I click the button. a popup window just flashed up and closed immediately. I've also tried to use OAuth.redirect and redirect it to http://oauth-io.github.io/oauth-js or my localhost, but then it says connection failed.
Is there something missing/wrong in the implementation?
Thanks a lot for the help.
PS: I'm working on localhost and i've tried to set redirect-url to localhost:portnr. but still failed. :(
Here is the sample code i've written:
Html:
<div><button onclick="oauthPop()">Try OAuth-io</button></div>
JS:
var oauthPop = function() {
OAuth.initialize('my-pub-key-on-authio');
OAuth.popup('facebook', function(err, res) { // or OAuth.callback
// handle error with err
if (err) {
alert ("error")
} else {
// get my name from fb
res.get('/me').done(function(data) {
alert(data.name)
})
}});
}
OAuth.io needs to have jQuery loaded to make HTTP requests using the result of OAuth.popup(). It use jQuery.ajax() behind the scene to let you a well-known function with all the option you might need.

Categories

Resources