I am playing with google api. This code is from codeacademy.
Here is HTML
<!DOCTYPE html>
<html>
<head>
<script src="app.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
Here is javascript:
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
console.log("onYouTubeApiLoad");
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('1111111111AIzaSyBenRS7G9WPDylh2JAXOeD2uLsao6VW2QY');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'surfboards'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
It's suppose to work fine. But I don't know why - function onYouTubeApiLoad() - is never called. What is wrong? Can't figure out.
Related
I've been successfully using this URL to pull data from Google Sheets in JSON:
https://spreadsheets.google.com/feeds/cells/<SHEETS_ID>/1/public/full?alt=json
I want to get the JSON for a Google Docs document now. What would the URL be to do that?
I know I can use the GET API, but I'm trying to do this using simple AJAX and no OAuth (the file is public)
Answer:
While the Google Spreadsheets Data API that hosts the https://spreadsheets.google.com/feeds/cells/<SHEETS_ID>/1/public/full?alt=json endpoint is still live, the Google Docs one is not and obtaining a Doc in JSON format in this way is no longer possible.
More Information:
The endpoint you are referencing to obtain Sheets data as a JSON structure is part of the Google Data APIs and is one of Google's older APIs - most of which have been replaced with newer APIs. The Spreadsheets one, as you can see here, is still live, where there is an interactive example explaining how to form this URL.
As you can see in the GData API Directory documentation however, the Google Documents List Data API has been shut down and replaced by the Google Drive API. Unfortunately, this means that the method you are looking for has been deprecated and so using either the Drive or Docs APIs now need to be used.
References:
Simple example of retrieving JSON feeds from Spreadsheets Data API
Google Data APIs - GData API Directory
Google Drive API
You can find that information in Google Docs API code samples here.
Specifically it is a GET request to https://docs.googleapis.com/v1/documents/{documentId}.
If successful, the response body contains an instance of Document which you can convert as JSON.
Example in Javascript:
<!DOCTYPE html>
<html>
<head>
<title>
Docs API Extract Body
</title>
<meta charset="utf-8"/>
</head>
<body>
<p>
Docs API Extract Body
</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>'
var API_KEY = '<YOUR_API_KEY>';
// Array of API discovery doc URLs for APIs used by the sample
var DISCOVERY_DOCS = [
'https://docs.googleapis.com/$discovery/rest?version=v1'];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/documents.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
printDocBody();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Prints the JSON body of a document.
*/
function printDocBody() {
gapi.client.docs.documents.get({
documentId: 'DOCUMENT_ID'
}).then(function(response) {
var doc = response.result;
appendPre(JSON.stringify(doc.body, null, 4));
},function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async="" defer="" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()" src="https://apis.google.com/js/api.js"></script>
</body>
</html>
I'm using the LinkedIn Javascript API to sign in users to my application, however the API is not returning the email address even though I'm requiring permission for that specific field. I'm including the API script as follows:
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: API_KEY
scope: r_fullprofile r_emailaddress
</script>
then I'm including the Log In button in the markup:
<script type="in/Login" data-onAuth="onLinkedInAuth">
and finally I have a function to add the callback for the API response:
function onLinkedInAuth() {
var fields = ['first-name', 'last-name', 'email-address'];
IN.API.Profile("me").fields(fields).result(function(data) {
console.log(data);
}).error(function(data) {
console.log(data);
});
};
I'm only getting the First and Last Name but the API doesn't return the email field.
Reference: https://developer.linkedin.com/documents/profile-fields#email
1- be sure you made email permission (r_emailaddress) in your app http://developer.linkedin.com/documents/authentication#granting
2- then you may use this
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: key
**onLoad: onLinkedInLoad**
authorize: true
</script>
<script>
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
// 2. Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("first-name", "last-name", "email-address").result(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
}
</script>
hope this will help you :)
thanks
Hello there #Ulises Figueroa,
May be I am coming in a bit late but this is how I had got this done:
Start off with the initial script tag on the top of your page within the head section:
<script>
Client Id Number here:
onLoad: onLinkedInLoad
authorize: true
</script>
Then, in your JS File,(I had placed an external JS File to process this API sign up/ Auth), have the following details placed:
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function getProfileData(){
IN.API.Profile("me").fields(["firstName","lastName", "email-address", "positions"]).result(function(data) {
var profileData = data.values[0];
var profileFName = profileData.firstName;
var profileLName = profileData.lastName;
if(data.values[0].positions._total == "0" || data.values[0].positions._total == 0 || data.values[0].positions._total == undefined) {
console.log("Error on position details");
var profileCName = "Details Are Undefined";
}
else {
var profileCName = profileData.positions.values["0"].company.name;
}
var profileEName = profileData.emailAddress;
//console.log all the variables which have the data that
//has been captured through the sign up auth process and
//you should get them...
});
}
Then last but not the least, add the following in your HTML DOCUMENT which can help you initiate the window popup for the linkedin auth sign up form:
<script type="in/Login"></script>
The above setup had worked for me. Sure this will help you out.
Cheers and have a nice day.
Implementation looks good. I'd believe this is a result from the profile's privacy settings. Per linked-in's docs:
Not all fields are available for all profiles. The fields available depend on the relationship between the user you are making a request on behalf of and the member, the information that member has chosen to provide, and their privacy settings. You should not assume that anything other than id is returned for a given member.
I figured out that this only happens with certain LinkedIn accounts, so this might be caused because some privacy setting with the email. I couldn't find any reference to the documentation so I had to consider the case when email field is not available.
I am building a website using the Twitter and Facebook JavaScript SDKs. I am attempting to perform tweets and facebook shares from the site. But I am getting the following error when I try to send a tweet OR facebook share from my website:
Chrome:
Unsafe JavaScript attempt to access frame with URL http://edro.no-ip.org:3000/#_=_ from frame with URL http://platform.twitter.com/widgets/tweet_button.1354761327.html#_=1355186876357&count=none&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fedro.no-ip.org%3A3000%2F%23_%3D_&related=xbox%3AGhostfire%20Games&size=m&text=Check%20out%20this%20fun%20story!%20%23atalltale&url=http%3A%2F%2Fedro.no-ip.org%3A3000%2Fstories%2FiqU9xW1FJI. The frame requesting access set 'document.domain' to 'twitter.com', but the frame being accessed did not. Both must set 'document.domain' to the same value to allow access.
Safari:
Unsafe JavaScript attempt to access frame with URL http://edro.no-ip.org:3000/ from frame with URL http://platform.twitter.com/widgets/tweet_button.1354761327.html#_=1355197702032&count=none&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fedro.no-ip.org%3A3000%2F&related=xbox%3AGhostfire%20Games&size=m&text=Check%20out%20this%20fun%20story!%20%23atalltale&url=http%3A%2F%2Fedro.no-ip.org%3A3000%2Fstories%2FiqU9xW1FJI. Domains, protocols and ports must match.
Here's the code (I only included the relevant parts):
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>Title</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
</body>
<center>
<h1>Page Header</h1>
 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<div id="fb-root"></div>
<script type="text/javascript">
// Once the Facebook SDK is fully loaded, this callback will be invoked
window.fbAsyncInit = function()
{
FB.init({
appId: "250634021702621",
status: true,
cookie: true,
channelUrl: '//edro.no-ip.org:3000/channel.html',
});
FB.Event.subscribe('auth.statusChange', handleStatusChange);
};
// Callback for once we are logged in and authorized
function handleStatusChange(response) {
document.body.className = response.authResponse ? 'connected' : 'not_connected';
if (response.authResponse)
{
}
};
// Declare a generic SDK loading function
var loadSDK = function(doc, script, id, src)
{
var js, fjs = doc.getElementsByTagName(script)[0];
if (!doc.getElementById(id))
{
js = doc.createElement(script);
js.id = id;
js.src = src;
js.async = true; // Makes SDK load asynchronously
fjs.parentNode.insertBefore(js,fjs);
}
};
// Twitter SDK loading
loadSDK(document, 'script', 'twitter-wjs', 'https://platform.twitter.com/widgets.js');
// Facebook SDK loading
loadSDK(document, 'script', 'facebook-jssdk', '//connect.facebook.net/en_US/all.js');
// Facebook callback - useful for doing stuff after Facebook returns. Passed as parameter to API calls later.
var myResponse;
function callback(response)
{
if (response)
{
// For debugging - can query myResponse via JavaScript console
myResponse = response;
if (response.post_id)
{
}
else
{
// Else we are expecting a Response Body Object in JSON, so decode this
var responseBody = JSON.parse(response.body);
// If the Response Body includes an Error Object, handle the Error
if(responseBody.error)
{
}
// Else handle the data Object
else
{
}
}
}
}
// All API calls go here
$(document).ready(function ()
{
// Post to your wall
$('#post_wall').click(function ()
{
FB.ui(
{
method: 'feed',
// useful if we want the callback to go to our site, rather than the JavaScript, so we can log an event
redirect_uri: 'http://edro.no-ip.org:3000',
link: 'http://edro.no-ip.org:3000/stories/{game.id}',
picture: 'http://fbrell.com/f8.jpg',
name: 'name',
caption: 'caption',
description: 'description'
// display: 'popup'
},
callback
);
return false;
});
});</script>
<!-- Tweet code-->
Tweet
<!-- Facebook share code-->
<p id="msg">Share on Facebook</p>
</center>
</html>
"Domains, protocols and ports must match."
Typical mismatch in (older versions of ?) Safari is http://www.example.com and http://example.com.
I'm making a chrome extension, which needs to get the current user's followers. The tumblr API says that I need to implement oauth and send requests as listed here. I implemented oauth following the example and using the library from google here.
So, the result was that the oauth.authorize function would run, but the callback function, onFollowers, wouldn't be called, leaving me to believe that I'm not getting a response from tumblr for some reason.
This is the code I ended up with:
background.html:
<html>
<script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="chrome_ex_oauth.js"></script>
<script type="text/javascript" src="background.js"></script>
</html>
background.js:
var oauth = ChromeExOAuth.initBackgroundPage({
'request_url' : 'POST http://www.tumblr.com/oauth/request_token',
'authorize_url' : 'http://www.tumblr.com/oauth/authorize',
'access_url' : 'POST http://www.tumblr.com/oauth/access_token',
'consumer_key' : '[key provided]',
'consumer_secret' : '[secret provided]',
'app_name' : '[app name]'
});
var followers = null;
var baseHostname = localStorage.getItem('BaseHostname');
function onFollowers(text, xhr) {
//parsing JSON response
}
function getFollowers() {
oauth.authorize(function() {
var url = "api.tumblr.com/v2/blog/"+baseHostname+"/followers";
oauth.sendSignedRequest(url, onFollowers, {
'parameters' : {
'base-hostname' : baseHostname
}
});
});
};
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "getFollowers")
console.log(baseHostname);
getFollowers();
sendResponse({farewell: "getFollowers function run success"});
});
Am I missing something?
See here:
Making a POST request to Tumblr's API inside a Chrome Extension
Could be that you
sendSignedRequest
Should have the params the other way around? First method, than url ?
I am an iOS and PhoneGap newbie. I have the index.html file and a javascript file called MyClass.js.
In my MyClass.js, I have a function -
var MyClass = {
testfunc: function() {
navigator.notification.alert("Success : \r\n");
}
}
I am trying to call it from the index.html function like -
MyClass.testfunc();
In my Phonegap.plist file I have an entry MyClass-Myclass as a key-value pair with the type String. However I don't get the alert. What am I doing wrong?
Have you included the following in your index.html:
<script src="MyClass.js"></script>
This will allow you to use the MyClass.js functions in your index.html file
Your markup for your alert is wrong...
navigator.notification.alert(
'Some Alert Text here', // alert message
successCallback, // callback function
'Alert Title, // alert title
'OK' // button text
);
Hi can you try following code:
// MyClass.js
var MyClass = {
testFunction: function() {
alert("hi there");
}
};
// index.html
<html>
<head>
</head>
<body>
<script src="MyClass.js"></script>
<script src="phonegap-1.3.0.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready", function() {
navigator.notification.alert("hi there \r\n");
//alert("hi there \r\n");
});
</script>
</body>
</html>