So I'm trying to experiment with accessing my google spreadsheet using JS, and I'm a beginner, and probably way in over my head, but I need help
So I have this script
<!DOCTYPE html>
<html>
<head>
<title>Google Sheets API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Sheets API Quickstart</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" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'CLIENT_ID';
var API_KEY = 'API_KEY';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.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;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* 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';
listMajors();
} 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);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: 'ID',
range: 'Class Data!A1:A1',
}).then(function(response) {
var range = response.result;
console.log(range);
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
listMajors()
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Basically what I'm trying to do here is to access my spreadsheet and print the first column of the first row as a range of (A1 to A1), and my function listMajors() is supposed to do it, but I'm struck with this error
"<a class='gotoLine' href='#144:9'>144:9</a> Uncaught ReferenceError: gapi is not defined"
You are calling listMajors before the script tag with src="https://apis.google.com/js/api.js" is actually loaded. The reason for that is that gapi is being set up asynchronously.
In this case, listMajors() at the end of the script tag is being executed before gapi is even loaded. You are already calling it in the updateSigninStatus so I'm guessing that it will be properly called if you remove that line.
Note that I haven't looked into the code in that function (and you should probably make another question if that doesn't work and you can't figure why).
gapi needs to be loaded and you need to be authenticated, before your code can work. So the earliest place in your code, where you could call listMajors() would be in handleAuthClick():
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn().then(function() {
listMajors();
}, function() {
appendPre('Error while authenticating');
});
}
Don't forget to remove the two(!) existing calls to listMajors() from your code.
Related
I am integrating google-docs in my application using angular. I followed below google-docs API link which is provided in the format of Javascript
https://developers.google.com/docs/api/quickstart/js
<!DOCTYPE html>
<html>
<head>
<title>Google Docs API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>
Google Docs API Quickstart
</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 quickstart
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';
printDocTitle();
} 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 title of a sample doc:
* https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
*/
function printDocTitle() {
gapi.client.docs.documents.get({
documentId: '195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE'
}).then(function(response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, 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 am trying to migrate this from Javascript to an Angular application. the problem here's gapi.load() and other places also used gapi object name which is not declared in javascript. I am not good at advanced javascript, I don't find anywhere how to import gapi.
Someone, please help me
Below node package wraps the Gapi into a service layer allowing to work with Gapi in an Angular 9+ project.
npm install ng-gapi
Follow the npm package link for more information.
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 have built a javascript code to be able to read any Youtube video transcript (gapi.client.youtube.captions.download). The auth 2.0 works fine, I run my app in a local web server everything is fine, the problem is that when I run the request I have the error 403: cb=gapi.loaded_0:164 GET https://content.googleapis.com/youtube/v3/captions/My_API_Key 403 I have not found any solution here in StackOverflow.. any idea ?
Here is my js file:
const CLIENT_ID = 'My_Client_ID';
const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';
const authorizeButton = document.getElementById('enter-button');
const signoutButton = document.getElementById('exit-button');
const content = document.getElementById('content');
// default youtube channel
const defaultChannel = 'googledevelopers';
// Load auth2 library
function handleClientLoad(){
gapi.load('client:auth2', initClient);
}
// Init API client library and set up sing in listeners
function initClient(){
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(() => {
// Listen for sing state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignouClick;
});
}
// update UI sign in state changes
function updateSigninStatus(isSignedIn){
if(isSignedIn){
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
content.style.display = 'block';
getChannel(defaultChannel);
}else{
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
content.style.display = 'none';
}
}
// Handle Login
function handleAuthClick(){
gapi.auth2.getAuthInstance().signIn();
}
// Handle Logout
function handleSignouClick(){
gapi.auth2.getAuthInstance().signOut();
}
// Display channel Data
function showChannelData(data){
const channelData = document.getElementById('channel-data');
channelData.innerHTML = data;
}
// Get channel from API
function getChannel(channel){
gapi.client.youtube.captions.download({
id: 'guMGyC1tUYAdL3hgBlcGnW4Rt_bBUbtp'
})
.then(response => {
console.log(response);
const channel = response.result.items[0];
})
.catch(err => alert('No Channel By THat Name'));
}
And here is my index.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your awesome Youtube search engine</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Awesome videos!" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<header>
<h1 class="w100 text-center">YouTube Viral Search</h1>
</header>
<div class="container">
<p>Login with Google</p>
<button class="btn green" id="enter-button">Log In</button>
<button class="btn green" id="exit-button">Log Out</button>
<br />
<div id="content">
<div class="row">
<div id="channel-data" class="col s12"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="/javascripts/appYT.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
enter code here
You can use the following code for get the transcript in a given video.
This is the working jsfiddle
N.B here I have the videoId zenMEj0cAC4, but you can change it as you desire.
$.ajax({
type: "GET",
url: "https://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
crossDomain: true,
}).done(function(data) {
console.log(data);
getCaption(data);
});
var parser, xmlDoc;
var HTML_captions = "";
// Parse the AJAX response and get the captions.
function getCaption(ajax_response) {
try {
parser = new DOMParser();
xmlDoc = parser.parseFromString(ajax_response, "text/xml");
//console.log(ajax_response);
//console.log(xmlDoc.getElementsByTagName("transcript").length);
if (xmlDoc.getElementsByTagName("transcript").length > 0) {
// Loop the results of the xmlDoc:
for (var i = 0; i < xmlDoc.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
} else {
// Loop the results of the ajax_response;
for (var i = 0; i < ajax_response.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
}
document.getElementById("demo").innerHTML = "<i>Preparing captions...</i>";
setTimeout(fillData(), 2000);
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at getCaption function - see console form more details.');
alert('Error at getCaption function - see console form more details.');
}
}
// Fill the data "captions" in a HTML "div" control.
function fillData() {
try {
document.getElementById("demo").innerHTML = HTML_captions;
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at fillData function - see console form more details.');
alert('Error at fillData function - see console form more details.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="demo"><i>Loading captions...</i></div>
Just in case you need more information about how you can get automatic closed captions, you can refer to these answers in Stack Overflow:
Get closed caption “cc” for Youtube video
Extract automatic captions from YouTube video
I'm working on a website where the client has asked for an option to allow signup/login using Google and Facebook accounts. How can I extract the email address from a user's Google profile for storing in database?
Here is my code. The problem is that I am not getting the user profile completely. Instead, I am receiving just user name.
try
{
WebClient client = new WebClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ access_token;
string outputData = client.DownloadString(urlProfile);
GoogleUserOutputData serStatus =
JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
return serStatus;
// You will get the user information here.
}
}
catch (Exception ex)
{
//catching the exception
}
return null;
Here is a way to receive data (email, etc.) in JavaScript. At the end it shows an alert with data. (You can store this data in a database.) It's a complete working example with a Google button.
<html>
<head>
<title>Demo: Getting an email address using the Google+ Sign-in button</title>
<!-- Include the API client and Google+ client. -->
<script src = "https://plus.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!-- Container with the Sign-In button. -->
<div id="gConnect" class="button">
<button class="g-signin"
data-scope="email"
data-clientid="Your_Client_ID"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
<!-- Textarea for outputting data -->
<div id="response" class="hide">
<textarea id="responseContainer" style="width:100%; height:150px"></textarea>
</div>
</div>
</body>
<script>
/**
* Handler for the signin callback triggered after the user selects an account.
*/
function onSignInCallback(resp) {
gapi.client.load('plus', 'v1', apiClientLoaded);
}
/**
* Sets up an API call after the Google API client loads.
*/
function apiClientLoaded() {
gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
}
/**
* Response callback for when the API client receives a response.
*
* #param resp The API response object with the user email and profile information.
*/
function handleEmailResponse(resp) {
var primaryEmail;
var name;
var gender;
for (var i=0; i < resp.emails.length; i++) {
if (resp.emails[i].type === 'account')
primaryEmail = resp.emails[i].value;
if (resp.displayName != null)
name = resp.displayName;
gender = resp.gender;
}
document.getElementById('responseContainer').value = 'Primary email: ' +
primaryEmail + '\n\nFull Response:\n' + JSON.stringify(resp);
ShowAlert("Email: "+primaryEmail +" "+"Name: "+ resp.displayName +" "+"Gender: "+gender);
}
</script>
</html>
For further information and detail you can (should) read this link:
Getting people and profile information
Documentation is the key; please check it completely.
https://developers.google.com/identity/sign-in/web/sign-in
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}
Sign out
<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Google Sheets API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>Google Sheets API Quickstart</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>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.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({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
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';
listMajors();
} 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);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Admittedly, I'm relatively new at much of this.
But I'm trying to create a simple landing page that is connected to a Google Sheet. I want to host it as a subdomain off of my main website. However, I can't seem to get it to actually load the information. It works fine when I run it locally, but something seems to be stopping it in the browser.
I've also tried to get their own example code to run off of my website, but it has the same problem and error message.
The error I keep getting appears to be the following:
"Not a valid origin for the client."
error: "idpiframe_initialization_failed"
To see what it is doing, check out http://thomasconant.com/teamStats2.html
Does anyone recognize this error and can suggest what I can do to fix it?
You forgot to replace YOUR_CLIENT_ID with the actual client id you got.
What does your page which generates this error look like? It's hard to say without the code.
If you're using the Google API Client in Javascript, and this is a console error, I'm thinking that you have not added the correct origin to your Google Developer Console.
Error: origin_mismatch
This error will occur during the authorization flow if the host and port used to serve the web page doesn't match an allowed JavaScript origin on your Google Developers Console project. Make sure you completed the Step 1.e and that the URL in your browser matches.
(If this is the correct answer, don't forget to mark it!) :)