Gives me this error in gplus-api using JS - javascript

Hello i just started learning gplus-api signin using javascript but i came across a error that says this Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
This is my code i have referred to this site but didn;t help me! https://developers.google.com/+/web/signin/javascript-flow
My code
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
<meta name="google-signin-clientid" content="MY_CLIENT_ID.apps.googleusercontent.com">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-requestvisibleactions" content="http://schema.org/AddAction" />
<meta name="google-signin-cookiepolicy" content="single_host_origin" />
<script type="text/javascript">
(function(){
var po = document.createElement('script');
po.type = "text/javascript";
po.async = true;
po.src = "https://apis.google.com/js/client:plusone.js";
var s = document.getElementByTagName('script');
s.parentNode.insertBefore(po,s);
});
function render() {
// Additional params including the callback, the rest of the params will
// come from the page-level configuration.
var additionalParams = {
'callback': signinCallback
};
// Attach a click listener to a button to trigger the flow.
var signinButton = document.getElementById('signinButton');
signinButton.addEventListener('click', function() {
gapi.auth.signIn(additionalParams); // Will use page level configuration
});
}
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
<button id="signinButton">Sign in with Google</button>
</body>
</html>
my js origin is http://localhost:8080, also when i try to load this url it gives me 404 error
please help to solve me this error!

You must run a web server (even locally) when working with Google+ Sign in. A simple example is to run Python with your port set to 8080:
python -m SimpleHTTPServer 8080
You can also configure / run Apache or another server for local testing.

Related

Javascript button onclick event not triggered [duplicate]

I'm starting with Node.js and I have already a problem in my first program. Below is the code I'm using. Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Temperatures</title>
</head>
<body>
<input type="text" id="tb" name="tb" />
<input type="button" value="Random Number!" id="myButton" name="myButton"/>
<script src="client.js"></script>
</body>
</html>
Client.js:
const textBox = document.getElementById('tb');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
var rnd = Math.floor(Math.random() * 100);
textBox.value = rnd;
});
Server.js:
var app = require('http').createServer(response);
var fs = require('fs');
app.listen(8080);
console.log("App running…");
function response(req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Failed to load file index.html');
}
res.writeHead(200);
res.end(data);
});
}
When I start the application I go to the browser the text box and the button appear. But in the browser console I'm getting these errors:
client.js:1 Uncaught SyntaxError: Unexpected token <
ContentScript.js:112 Exception in onResRdy: TypeError: Cannot read
property 'htmlRes' of undefined
localhost/:1 Unchecked runtime.lastError: Could not establish
connection. Receiving end does not exist.
I guess my problem is the linking between the 3 files but I tried several things and I can't solve the problem. I'm sure it's a stupid error but forgive me I'm just getting start. Any advice?
The browser (because you have <script src="/client.js">) makes a request for /client.js
The server:
Gets the request
Runs response
Reads index.html
Sends it to the browser
Since index.html starts with <, the browser throws an error when it tries to run it as JavaScript.
Why are you giving the browser index.html when it asks for client.js?
You need to examine the request object, determine what URL is being asked for, write logic to return the correct resource with the correct status code and the correct content-type, and then return that to the client.
The Node.js documentation has an example of this but you should probably stop trying to use createServer directly — since it involves a massive amount of wheel reinvention — switch to using Express and work through the (very short) getting started guide which includes a section on using the static module to serve up static files.

SignalR inside an iframe not receiving

My web application that utilizes signalR sent from an API hub works well on all browsers. Now, when I try to add the link of my web application inside an iframe within a basic html page, my web application does not execute my connection methods.
Here a snippet of my code in my web application:
$.connection.hub.url = 'myUrl';
$.connection.hub.logging = true;
var varHub= $.connection.MyHub;
$.connection.hub.start()
.done(function () { console.log("Signal R connected"); //this is being executed })
.fail(function () { console.log("Could not Connect to signal R hub!"); });
$.connection.hub.disconnected(function () {
setTimeout(function () {
$.connection.hub.start();
}, 5000); // Re-start connection after 5 seconds
});
//Methods to be called by the server for signal R connections
varHub.client.start= function () {
//this is not being called
//do something
};
As I have said I have no problems when I directly access it via url. The issue only happens when I try to insert the url in an iframe.
Here's how I do it:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=11">
</head>
<body width="1280" height="736" style="margin:0;padding:0;overflow:hidden;border:0px;background:#000000;">
<iframe
src="http://myUrl/Home/Index?Id=someId" style="width:1280px;height:720px;margin:0;paddin:0;overflow:hidden;border:0px;"/>
scrolling="no"/>
</body>
</html>
Note: My target browser is IE 11.
Any ideas will be a great help! Thanks.
For anyone who will might encounter this in the future, this parameter fixed my issue.
Source: Here
Negotiating a transport takes a certain amount of time and client/server resources. If the client capabilities are known, then a transport can be specified when the client connection is started. The following code snippet demonstrates starting a connection using the Ajax Long Polling transport, as would be used if it was known that the client did not support any other protocol:
$.connection.hub.start({ transport: 'longPolling' })

Javascript working in Google Chrome but Blocked in IE

Using the code from here for testing. The javascript runs just fine in Google Chrome and Firefox but not in IE.
Ok so it works in IE if I run the html file locally but it does give me a warning at the bottom of the page saying it has disabled some scripts on the page and I have to click it to enable them.(doesnt happen in chrome) but ok I do that and it works. But I then put it on my remote webserver which just hosts the HTML file. The connection is still going to be local to the browser viewing the site. However this wont work in IE but could be because it doesn't even show a warning about the script. The page loads but the js doesn't run.
Im assuming that IE is blocking it by default.
How can I get round this and make it work like it does in chrome. The html/js is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
function connect() {
var ws = new WebSocket("ws://localhost:8080/service");
ws.onopen = function () {
alert("About to send data");
ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
alert("Message sent!");
};
ws.onmessage = function (evt) {
alert("About to receive data");
var received_msg = evt.data;
alert("Message received = "+received_msg);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
};
</script>
</head>
<body style="font-size:xx-large" >
<div>
Click here to start connection</div>
First Open program
</body>
</html>
UPDATE:
Thanks to adam i have checked the f12 Developer console and I get an error:
SCRIPT5022: SecurityError
Thanks to the people that have helped.
The Problem is to do with IE and Edge browser not wanting to connect to "Localhost" however if you change Localhost to 127.0.0.1 it works perfectly.
Updated Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
function connect() {
var ws = new WebSocket("ws://127.0.0.1:8080/service");
ws.onopen = function () {
alert("About to send data");
ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
alert("Message sent!");
};
ws.onmessage = function (evt) {
alert("About to receive data");
var received_msg = evt.data;
alert("Message received = "+received_msg);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
};
</script>
</head>
<body style="font-size:xx-large" >
<div>
Click here to start connection</div>
First Open program
</body>
</html>
Change
ws://localhost:8080/service
to
ws://{your_remote_domain_host}:8080/service
and it should work

gapi.auth.authorize callback doesn't get called when doing sign-in via Google on node-webkit app

I have an issue when doing sign-in from node-webkit app. In the node-webkit application, I open a page on my domain with the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<link rel="stylesheet" src="style.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.email';
function authorization() {
gapi.auth.authorize({
client_id: CLIENT_ID,
immediate: false,
scope: SCOPE
}, function(authResult) {
alert('CALLBACK');
}
);
}
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=authorization"></script>
<title>Google Sign In</title>
</head>
<body></body>
</html>
For some reason the callback never fires when running on node-webkit. While trying to debug it I saw something strange. When I run this from node-webkit, this code will open the google sign-in screen. When the node-webkit developer console is open for the google page, the callback fires successfully.
When I load the same page on chrome, the callback fires and I can see the alert, so I don't think the issue is with the code. Before running this code I programmatically clean the node-webkit cache so each time the user is required to enter his credentials.
Eventually I solved this using a different approach. Since this question was left unanswered for over 2 months now, I will describe which workaround I've used.
Instead of doing the sign-in using Google js library, I used server side authentication. I chose the Google PHP SDK. This is the flow I used:
From node-webkit, I opened a page (php) from my server on a new window.
exports.login_window = window.open(url,{
"position": "center",
"focus": true
});
using Google SDK, I generated an authentication link and redirected the client to that link.
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$authUrl = $client->createAuthUrl();
header('Location: '.$authUrl);
once authenticated, the client redirected back to my server.
using google API I queried for all the information I needed. Than I stored the information on the document session
"sessionStorage.google_data = ".json_encode($data).";"
from the original page (when I opened the login window), I polled the new window session, and once the google_data was there, I pulled it and closed the window.
if (
typeof exports.login_window == "undefined" ||
exports.login_window.window == null ||
typeof exports.login_window.window.sessionStorage == "undefined" ||
typeof exports.login_window.window.sessionStorage.google_data == "undefined" ) {
setTimeout(function(){
check_3p_login();
},200);
} else {
var google_data = exports.login_window.window.sessionStorage.google_data;
// rest of the code
}

Running Web Socket Client side programming

I just read about web sockets and written this simple client side java script. But it doesn't give me any output even if I run on Chrome browser and I don't know what is the FAULT??
May be google.com doesn't support Web sockets??
<!DOCTYPE html>
<html>
<head>
<title>Web socket Experiment</title>
<script type="text/javascript">
function callWebSocket() {
var socket = new WebSocket("ws://www.google.com");
socket.onopen = function () {
alert("Hello, Connected To WS server");
};
socket.onmessage = function (e) {
alert("The message received is : " + e.data);
};
socket.onerror = function (e) {
alert("An error occured while connecting... " + e.data);
};
socket.onclose = function () {
alert("hello.. The coonection has been clsoed");
};
}
</script>
</head>
<body>
<input type="button" value="Open Connecton" onclcik="callWebSocket()" />
</body>
</html>
Please help..
Thanks
Sneha
you typoed onclcik in your input button. Other than that, your code should work fine, except as minitech mentioned in his comment, I don't think google currently has a web socket script setup for you to use. Try making your own server-side script to point to, or search for an existing 3rd party site example to play with (eg, quick google search and I found ws://echo.websocket.org which i tried your code on and it worked, other than the typo)

Categories