I am attempting THIS OFFICIAL GOOGLE EXAMPLE and am running into an empty object/array on the sign in callback. The ONLY modifications I have made to this from Google's examples are the console.logs the alerts and a small syntax error they had
I changed
auth2.grantOfflineAccess().then(signInCallback);
to
auth2.grantOfflineAccess().then(signInCallback());
Without the () the function wouldn't fire. and the made that alert would not display. Now having copied this DIRECTLY from Google's page, have I missed something or is there another bug that I missed?
Also worth noting -- The origins are set up:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html itemscope itemtype="http://schema.org/Article">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
client_id: 'xxxxxxxx.apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/plus.business.manage'
});
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function () {
// signInCallback defined in step 6.
alert('made this');
let test = auth2.grantOfflineAccess().then(signInCallback());
console.log(test);
});
function signInCallback(authResult) {
alert('made that');
console.log(authResult);
if (authResult['code']) {
// Send the code to the server
} else {
// There was an error.
}
}
</script>
</body>
</html>
My console.log(authResult); just inside the signInCallback() function is empty -> undefined. I am able to get my user logged in and the pop-up indicates all scopes are granted. Why am I not able to grab the access token?
Related
The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// 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() {
// This API key is intended for use only in this lesson.
// See link to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
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: 'clapton'
});
// 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);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.
I am trying to call this Javascript function. When I hit my button, there is nothing loading. I set an id for my button. With the onclick I load the function onLinkedInLoad. But is it not that function I should call to activate the script? Can anybody see what I am doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<button id="btn">Try Me</button>
<script type="text/javascript">
document.getElementById("btn").onclick = onLinkedInLoad;
</script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: myKey
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
</script>
</body>
</html>
Update:
I get this in my console:
18 Uncaught ReferenceError: onLinkedInLoad is not defined
www.linkedin.com/uas/js/userspace?v=0.0.1191-RC8.56309-1429&apiKey=myKey&authorize=true&onLoad=onLinkedInLoad&secure=1&:
22 Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
I putted my APIkey in also. I just replaced in the code here with "myKey". I also tried with .addEventListener('click', onLinkedInLoad), but still nothing happens
Try to load the function definition script before the call script. Or better, take all the scripts in another file and just load that on your HTML.
I've tried your code on js fiddle and it works by doing that.
I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>
I'm getting an Object doesn't support property or method error when I try to call a function in a dojo module. I have a main page and two modules. I call the first module from the main page and it works, I call the second module from the first and it works, but I get the error when I try to call the first module from the second. Here is my code:
main page:
<!DOCTYPE html>
<html >
<head>
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">
<script>
var dojoConfig = {
parseOnLoad:true,
async: true,
isDebug:true,
packages: [
{name: "Scripts", location: location.pathname.replace(/\/[^/]+$/, "") + "/Scripts"},
]
};
</script>
<script> src="http://js.arcgis.com/3.10/"></script>
<script>
require(["Scripts/Mod1", "Scripts/Mod2"],
function (Mod1, Mod2) {
Mod1.M1Method("call from main page");//works great
});
</script>
</head>
<body class="claro">
<div>look here you</div>
</body>
</html>
Module 1:
define(["Scripts/Mod2"],
function (Mod2) {
return {
M1Method: function (msg) {
alert(msg);
Mod2.M2Method("call from Mod1");//works great
},
M1Method2: function (msg) {
alert(msg);
}
}
});
Module 2:
define(["Scripts/Mod1"],
function (Mod1) {
return {
M2Method: function (msg) {
alert(msg);
Mod1.M1Method2("call from Mod2"); //JavaScript runtime error: Object doesn't support property or method 'M1Method2'
}
}
});
How can I make that call from Mod 2 to Mod1?
Thanks
You are trying to do a cyclic dependency. In module 2, use a require statement. Try something like this:
define(["require"],
function (require) {
return {
M2Method: function (msg) {
alert(msg);
try {
require(["Scripts/Mod1"], function(Mod1) {
Mod1.M1Method2("call from Mod2");
});
} catch (dohObj) {
alert('Doh!, this failed. Stupid answer: ' + dohObj.message);
}
}
}
}
);
Your html code has a typo in that you enclosed the 'script' tag too soon when including dojo.js. Should be something like
<script type="text/javascript" src="http://js.arcgis.com/3.10/"></script>
You need to fix that file first to properly include dojo and 'require()'.
Let's say I've the following sample code (JavaScript):
// Client A
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.publish("some:channel", { text: "hello world" });
});
// Client B (subscriber)
var conn = new XSockets.WebSocket([wsUri]);
conn.on(XSockets.Events.open, function (clientInfo) {
conn.on("some:channel", function(message) {
// Subscription receives no message!
});
});
Client B never receives a message. Note that this is a sample code. You might think that I don't receive the message because Client B got connected after Client A sent the message, but in the actual code I'm publishing messages after both sockets are opened.
The server-side XSocketsController is working because I'm using it for server-sent notifications.
What am I doing wrong? Thank you in advance!
It looks like you have mixed up the pub/sub with the rpc, but I cant tell for sure if you do not post the server side code as well.
But what version are you using? 3.0.6 or 4.0?
Once I know the version and have the server side code I will edit this answer and add a working sample.
EDIT (added sample for 3.0.6):
Just wrote a very simple chat with pub/sub.
Controller
using XSockets.Core.Common.Socket.Event.Interface;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace Demo
{
public class SampleController : XSocketController
{
/// <summary>
/// By overriding the onmessage method we get pub/sub
/// </summary>
/// <param name="textArgs"></param>
public override void OnMessage(ITextArgs textArgs)
{
//Will publish to all client that subscribes to the value of textArgs.#event
this.SendToAll(textArgs);
}
}
}
HTML/JavaScript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/XSockets.latest.min.js"></script>
<script>
var conn;
$(function() {
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Sample');
conn.onopen = function(ci) {
console.log('open', ci);
conn.on('say', function(d) {
$('div').prepend($('<p>').text(d.text));
});
}
$('input').on('keydown', function(e) {
if (e.keyCode == 13) {
conn.publish('say', { text: $(this).val() });
$(this).val('');
}
});
});
</script>
</head>
<body>
<input type="text" placeholder="type and hit enter to send..."/>
<div></div>
</body>
</html>
Regards
Uffe