I’m using Google Sign-In and have it working, albeit a bit too well. If the user is logged in to Google and opens my logon page the onSuccess() function is automatically triggered without the user pressing the Google logon button. This prevents them from logging in without Google. How can I stop onSuccess() from firing when the page is loaded and only fire when the button is pressed?
To recreate, replace MY_ID with a valid Google client ID, open this page, login and refresh. Each refresh will display user info in the browser console.
<html>
<meta name="google-signin-client_id" content="MY_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/api:client.js"></script>
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async="true" defer></script>
<script>
function renderButton()
{
gapi.signin2.render('googleBtn',
{
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
} );
}
function onSuccess(googleUser)
{
var authResponse = googleUser.getAuthResponse(true);
var profile = googleUser.getBasicProfile();
var expDate = new Date(authResponse.expires_at);
console.log('Expires Date: ' + expDate);
console.log('Access Token: ' + authResponse.access_token); // The Access Token granted.
console.log('Scope: ' + authResponse.scope);
console.log('Id Token: ' + authResponse.id_token);
console.log('Expires In: ' + authResponse.expires_in + " seconds"); // The number of seconds until the Access Token expires.
console.log('First Issued At: ' + new Date(authResponse.first_issued_at)); // The timestamp at which the user first granted the scopes requested.
console.log('Expires Date: ' + expDate);
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
}
</script>
<body>
<div align="center" id="googleBtn" class="customGPlusSignIn"></div>
</body>
</html>
I found another post here that answered the question. Using that I ended up with:
<script src="https://apis.google.com/js/client:platform.js?onload=googleInit" async="true" defer></script>
<meta name="google-signin-client_id" content="**********.apps..googleusercontent.com">
<script>
function googleInit()
{
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({});
element = document.getElementById('googleBtn');
auth2.attachClickHandler(element, {}, onSuccess, onFailure);
});
}
function onSuccess(googleUser)
{
var authResponse = googleUser.getAuthResponse(true);
var profile = googleUser.getBasicProfile();
}
function onFailure(error)
{
}
</script>
<html><body>
<div id="googleBtn" style="margin-bottom:30px;" align="center" class="g-signin2" data-width="240" data-height="50" data-longtitle="true" data-theme="dark"></div>
</body></html>
Related
We have an event that is set for an API that we are setting up. Initially, the event was pinging the API server continuously which brought our bounce rate way down. We added 'non_interaction': true to cancel out the bounce rate issue, but it doesn't seem to be working. In addition to adding 'non_interaction': true, are there any other settings in GA that need to be updated to make this work? Maybe we are missing something?
Thank you ahead of time for your help!
Here is the code for review:
<script>
(function () {
var GA_TRACKING_ID = 'xxxxxx';
function processMessage(event) {
console.log('processMessage: Received event:');
console.log('event.data:', event.data);
console.log('event.origin:', event.origin);
if (event.data.includes('"name"')) {
console.log('Received alert for mobile page', event);
}
else {
if (event.data.startsWith('R_')) {
// GTAG.js methods
// Maps 'dimension1' to 'response_id'.
gtag('config', GA_TRACKING_ID, {
'custom_map': {'dimension1': 'response_id'}
});
// Sends a response_id event.
gtag('event', 'ev_response_id', {
'response_id': event.data,
'non_interaction': true
});
console.log('Pushed response_id : ' + event.data + ' to Google Analytics.');
}
}
console.log('processMessage: end');
}
function setSessionId() {
var sessionIdName = 'ua_session_id';
var noFirstVisit = sessionStorage.getItem('noFirstVisit')
// this is the first time
if (!noFirstVisit) {
var sessionId = Math.random().toString(36).substring(2, 10);
gtag('config', GA_TRACKING_ID, {
'custom_map': {'dimension2': sessionIdName}
});
gtag('event', 'ev_session_id', {
'ua_session_id': sessionId,
'non_interaction': true
});
console.log('Pushed ' + sessionIdName + ': ' + sessionId + ' to Google Analytics.');
sessionStorage.setItem('noFirstVisit', true);
} else {
console.log('The user already saw this page.')
// close and reopen the tab to clear the session storage
}
}
window.addEventListener('message', processMessage);
setSessionId();
})();
</script>
How can I make it work for the current user and any editor user account? Even if I am logged on a normal user and on incognito on one of the editor accounts, it shows like I am speaking with myself because it enters on the
name != Admin.
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
if (name == "Admin") {
// Add the message to the page.
$('#discussion').append('<p style="color:green; text-align:left; width:500px"><strong><img = src="https://www.phplivesupport.com/pics/icons/avatars/public/avatar_7.png" title="Admin">'
+ ' </strong> ' + htmlEncode(message) + '</p>');
}
else if (name != "Admin") {
// Add the message to the page.
$('#discussion').append('<p style="color:blue;text-align:right;"><strong><img = src="https://www.phplivesupport.com/pics/icons/avatars/public/avatar_71.png" title="Peter">'
+ ' </strong> ' + htmlEncode(message) + '</p>');
}
};
// Get the user name and store it to prepend to messages.
var currentMember= '#Html.Raw(#ViewBag.Name)';
alert(currentMember);
$('#displayname').val(currentMember);
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
That's how it worked.
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
if (name == "true") {
// Add the message to the page.
$('#discussion').append('<p style="text-align:left; text-shadow: 2px 2px 3px red"><strong><img = src="/Images/admin_icon.png" title="Admin">'
+ ' </strong> ' + htmlEncode(message) + '</p>');
}
else if (name != "true") {
// Add the message to the page.
$('#discussion').append('<p style="text-align:right;text-shadow: 2px 2px 3px teal;"><strong>'
+ ' </strong> ' + htmlEncode(message) + '<img = src="/Images/client_icon.png" title="Client">' + '</p>');
}
};
// Get the user name and store it to prepend to messages.
var currentMember= '#(User.IsInRole("Administrator") ? "true" : "false")';
//alert(currentMember);
$('#displayname').val(currentMember);
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
I have fblogin to my site. I want to save ID, name and email to database. So PLease tell me how to pass the those values from
script to server. Since am dont have much experince, I dont know how to pass the values from script to server. If its possible
to pass the values from script ta server. Kindly tell me the solution.
Below I have posted my complete coding
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type="text/javascript">
// Load the SDK Asynchronously
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId: 'XXXXX', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
//var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/education ";
var uuu = "http://graph.facebook.com/me?education=" + response.authResponse.accessToken
FB.api('/me', function(me) {alert(me.first_name)
var Name = me.name;
var Email = me.email
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function() { FB.logout(function() { window.location.reload(); }); });
}
</script>
<form id="form1" runat="server">
<h1>
Facebook Login Authentication </h1>
<div id="auth-status">
<div id="auth-loggedout">
<div class="fb-login-button" autologoutlink="true" scope=" user_checkins,user_website, user_relationship_details, user_hometown, user_religion_politics, user_education_history, user_about_me, user_birthday, user_status, publish_stream, user_photos, read_stream, friends_likes">Login with Facebook</div>
</div>
<div id="auth-loggedin" style="display: none">
<br />
Name:<b><span id="auth-displayname"></span></b>
(logout)<br />
First Name: <b><span id="firstname"></span></b><br />
Last Name: <b><span id="lastname"></span></b><br />
Email: <b><span id="Email"></span></b><br />
gender: <b><span id="gender"></span></b><br />
Dob of birth: <b><span id="birth"></span></b><br />
Location: <b><span id="location"></span></b><br />
</div>
</div>
</form>
</body>
</html>
If you want to save the user info in the server, then you need to use some server side language..
Suppose you use PHP, then in that case, you need to pass user info to the server and first check whether user info exists in your db or not..
//connect with your database //request user info //query to get user
info from db
if(you have user info in database){ //display user profile }
else{
//upload to your database }
I have surfed the internet for last 2 days and found the soultion on my own to pass the value from client to server. Below I Have
pasted the solution...
<script type="text/javascript">
var data2Send = '{"fbid":"222222", "fbemail":"aaa#dsf.com", "fbsex":"Male", "fbdob":"22/03/1989"}';
$.ajax({
type: "POST",
url: 'passvaluw.aspx/Testmethod',
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {console.log(arg) //call successfull
$("#lbltxt").text(arg.d);},
error: function (xhr) {
//error occurred
}
});
</script>
[System.Web.Services.WebMethod]
public static string TestMethod(string fbid, string fbemail, string fbsex, string fbdob)
{
return fbemail;
}
I am trying to get nowelium / socket.io-titanium to work i have it working on the device but on website i get the following error in my console
XMLHttpRequest cannot load http://127.0.0.1:8080/socket.io/1/?t=1345807417891. Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.
I am using socket.io here is the chat.js server
var io = require('socket.io').listen(8080);
var archiveMessages = {};
var channels = ['foo channel', 'bar channel'];
var chat = io.of('/chat');
chat.on('connection', function(socket){
console.log('connected: %s', socket.id);
// push available channel list
socket.emit('available_channel', channels);
socket.on('join', function(value){
console.log('%s joined channel: %s', socket.id, value.channelId);
socket.join(value.channelId);
socket.set('channel_id', value.channelId, function(){
var messages = archiveMessages[value.channelId] || [];
socket.emit('joined', messages);
socket.broadcast.to(value.channelId).emit('user:join', {
id: socket.id
});
});
});
socket.on('post', function(message){
socket.get('channel_id', function(err, channelId){
console.log('%s says<%s channel>: %s', socket.id, channelId, message);
if(!(channelId in archiveMessages)){
archiveMessages[channelId] = [];
}
archiveMessages[channelId].push(message);
socket.emit('posted', {
message: message
});
socket.broadcast.to(channelId).emit('user:message', {
id: socket.id,
message: message
});
});
});
socket.on('disconnect', function(){
console.log('%s disconnected', socket.id);
socket.get('channel_id', function(channelId){
socket.leave(channelId);
socket.broadcast.to(channelId).emit('user:leave', {
id: socket.id
});
});
});
});
var image = io.of('/image');
image.on('connection', function(socket){
socket.on('upload', function(param){
console.log('upload base64 size: %d', param.base64.length);
if(param.download){
socket.emit('download', {
base64: 's' + new Array(65534).join('0') + 'e'
});
}
});
});
and here is the index.html i am running
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="height=device-height, width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>chat sample</title>
<style>
#rooms button {
display: block;
}
</style>
<script type="text/javascript" src="http://localhost:8080/socket.io/dist/socket.io.js"></script>
<script type="text/javascript">
var $ = function(id){
return document.getElementById(id);
};
window.addEventListener('load', function (){
var socket = io.connect('127.0.0.1:8080');
var chat = socket.of('/chat');
console.log(chat);
chat.on('available_channel', function(channels){
channels.forEach(function (channelId){
var button = document.createElement('button');
button.appendChild(document.createTextNode(channelId));
$('rooms').appendChild(button);
button.addEventListener('click', function(){
$('chat').style.display = '';
chat.emit('join', {
channelId: channelId
});
});
});
});
var addMessage = function(message){
var li = document.createElement('li');
li.appendChild(document.createTextNode(message));
$('messages').appendChild(li);
};
chat.on('joined', function(messages){
messages.forEach(function(message){
var li = document.createElement('li');
li.appendChild(document.createTextNode(message));
$('archives').appendChild(li);
});
});
chat.on('posted', function(value){
return addMessage('you posted: ' + value.message);
});
chat.on('user:join', function(value){
return addMessage(value.id + ' joined this channel');
});
chat.on('user:leave', function(value){
return addMessage(value.id + ' leaved this channel');
});
chat.on('user:message', function(value){
return addMessage(value.id + ' says ' + value.message);
});
$('submit').addEventListener('click', function (){
var messageValue = $('message').value;
if(/^\s+$/.test(messageValue)){
return;
}
chat.emit('post', messageValue);
$('message').value = '';
});
});
</script>
</head>
<body>
<div id="rooms">
</div>
<div id="chat" style="display:none">
<input type="text" id="message" value="" placeholder="message here" />
<input type="submit" id="submit" value="send" />
<p>archives</p>
<ul id="archives" style="color: #999"></ul>
<p>messages</p>
<ul id="messages"></ul>
</div>
</body>
</html>
CAn anyone tell me why this might be happening???
I wonder if switching it to localhost would fix that.
I researched into Access-Control-Allow-Origin and traced it to the web browser as the culprit if I remember correctly. I eventually started looking for a way to disable the browser from checking for that. In Chrome this is my shortcut path.
...Chrome\Application\chrome.exe --allow-file-access-from-files --disable-web-security
See if that works. I don't know if it really remedies the issue as much as it just suppresses the problem. If you were calling the web page from the host you were trying to access I don't think you'd have this problem at all. For example, when I attempt to access my web service on mydomain.com using the web page mydomain.com/myprogram.html it doesn't complain about cross domain access.
I found this useful codes in the net, but when I run the code and clicked "Published Wall Post" I got this error.
API Error Code: 191 API Error Description: The specified URL is not
owned by the application Error Message: redirect_uri is not owned by
the application.
How to fixed this code?
thanks
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '420291518023354', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login(){
FB.api('/me', function(response) {
document.getElementById('login').style.display = "block";
document.getElementById('login').innerHTML = response.name + " succsessfully logged in!";
});
}
function logout(){
document.getElementById('login').style.display = "none";
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'Thinkdiff.net contains geeky stuff', 'hrefTitle', 'http://localhost:3000/', "Share thinkdiff.net");
});
}
function share(){
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function(response) { console.log(response); });
}
function graphStreamPublish(){
var body = 'Reading New Graph api & Javascript Base FBConnect Tutorial';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
FB.api('/me', function(response) {
var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('name').innerHTML =
'Your name: ' + rows[0].name + "<br />" +
'<img src="' + rows[0].pic_square + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
}
);
}
</script>
<h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>
<p><fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button></p>
<p>
Publish Wall Post |
Share With Your Friends |
Publish Stream Using Graph API |
FQL Query Example
</p>
<textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
<br />
Status Set Using Legacy Api Call
<br /><br /><br />
<div id="login" style ="display:none"></div>
<div id="name"></div>
</body>
This is because facebook permissions. When you create a new FB app there is a field named "App Domains" you need to call the FB app only from that address or it won´t work.
For example if you have App Domain http://www.mysite.com and you are trying to access from http://mysite.com (without www), that error apperars.
I recommend you to store in "App Domains" all the possible combinations of your domain name, including alias and subdomains
Hope this help you