FB.login pop up is blocked when page on load - javascript

I'm facing an issue when calling FB.login when page on load, the FB.login pop up is block by the browser. Currently I know I've to call FB.login after a user click event but I've to do it this way due to the business logic from client.
FB.api('/me/permissions', function(response2) {
var permsArray = response2.data[0];
var permsNeeded = ["user_events"];
var permsToPrompt = [];
for (var i in permsNeeded) {
if (permsArray[permsNeeded[i]] == null) {
permsToPrompt.push(permsNeeded[i]);
}
}
if (permsToPrompt.length > 0) {
promptForPerms(permsToPrompt);
}
});
var promptForPerms = function(perms) {
FB.login(function(response) {
}, {scope: perms.join(',')});
};
Is there any solution to call FB.login() without user click event? Or is there any tweak for this? Appreciate for the help.

You're not going to be able to code your way around the popup blocker, unfortunately.
The way to solve this is by redirecting the user to the Facebook permissions dialog when the page loads as described in the docs for manually building a login flow.
You first need to detect if the user is authenticated / connected with your application already and only redirect if they are not connected. This is best done in the window.fbAsyncInit function like this:
window.fbAsyncInit = function() {
var myAppID = 'YOUR APPLICATION ID';
FB.init({ appId: myAppID });
FB.getLoginStatus(function(response) {
if ('connected' != response.status) {
window.location.href = 'https://www.facebook.com/dialog/oauth' +
'?client_id=' + myAppID +
'&scope=user_events' +
'&redirect_uri=' + encodeURIComponent(document.URL);
} else {
alert('welcome to my app');
}
});
};
The other option is to adjust your user journey slightly; perhaps if the user is not connected then you could display an overlay with a message asking them to authenticate and a button which when clicked calls FB.login.

Related

Authenticate on button click using jQuery

So I am stuck on a specific piece and I can't seem to figure it out, so what I'm attempting to do is that I have a button and when it's clicked, it will open the link in the window and the users will authenticate and then it will redirect back to the page with a code from Instagram.
What I'm attempting to do:
When someone clicks on the #insta-auth button, it will open the getAuthentication function link in the same tab.
So let's say that window.location.origin is https://test.com/, the Instagram URL will return it as https://test.com/?code=debsfbdfb.
For some reason, I attempted onclick="" and $().onClick and nothing has worked so far, all help would be appreciated!
The snippet shows the button.
// Setup out Instagram object
var FHInstagram = window.FHInstagram || {};
FHInstagram.name = "";
FHInstagram.version = "2.0.0";
(function ($, window, document, undefined) {
// Define our Instagram object
const Instagram = {
APP_ID: '32222516',
API_URL: 'https://graph.instagram.com/',
API_OAUTH: 'https://api.instagram.com/oauth/authorize',
API_OAUTH_TOKEN_URL: 'https://api.instagram.com/oauth/access_token',
API_FIELDS: 'caption,media_url,media_type,permalink,timestamp,username',
// Authenticate Instagram
getAuthentication: function () {
return "https://api.instagram.com/oauth/authorize?client_id=" + this.APP_ID + "&redirect_uri=" + window.location.origin + "&scope=user_profile,user_media&response_type=code";
},
};
})(jQuery, window, document);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="insta-authenticate">Authenticate Instagram</button>
$('#insta-authenticate').on('click', function() {
-- do your instagram stuff here, getAuthentication();
}

JavaScript - Trigger Twitter intent "follow" callback only if user actually follows

Product I am working on: Requestly - Chrome and Firefox Extension Setup redirects, modify headers, switch hosts, insert user scripts (https://www.requestly.in/)
What I am trying to do: Requestly offers free 30 days access to GOLD Plan if user completes a set of few steps. One of such steps is to follow us on Twitter. I want to verify if the user has actually followed us on Twitter.
//After loading widgets.js
function followIntent (intentEvent) {
console.log("User Followed")
};
twttr.ready(function (twttr) {
twttr.events.bind('follow', followIntent);
});
Problem: The "followIntent" function is getting triggered as soon as user clicks the Follow button. I want it to be called only after user has successfully followed us. How can I achieve this?
Assuming you're running into a problem that the follow event occurs in between the events of user clicking the "following" button and the actual "following" happens. You can always call the Twitter API to verify it via GET followers/ids. Though it seems a bit unnecessary...
function followIntent (intentEvent) {
if (!intentEvent) return;
followerVerification(intentEvent.data.user_id);
};
async function followerVerification (userID) {
// make your API request here
var userList = await twitterAPIRequest();
if (userList.includes(userID)){
console.log("User Followed")
} else {
console.log("User Not Followed")
}
}
function twitterAPIRequest() {
var settings = {
"async": true,
"url": "https://api.twitter.com/1.1/followers/ids.json?screen_name=twitterdev",
"method": "GET",
"headers": {
// Your app autherization stuff
}
}
$.ajax(settings).done(function (response) {
return response.ids;
});
}
twttr.ready(function (twttr) {
twttr.events.bind('follow', followIntent);
});

Get access token of instagram API

I want to get the access token in order to diaply the images of an account. So I display a pop up where the user can connect. The pop up works but it redirects to instagram site, with the user connected instead of send me the code. The link to the connection is something like :
https://www.instagram.com/accounts/login/?force_classic_login=&next=/oauth/authorize/%3Fclient_id=aaaaaaaa&redirect_uri=url&response_type=token
I log in and then, it redirects me to :
https://www.instagram.com/oauth/authorize/?client_id=aaaaaaa&redirect_uri=url&response_type=token
I don't understand how I can get the code. And I also used the exact same code as : https://github.com/radykal/instagram-popup-login
Can someone help me please ?
EDIT
var loc = window.location.host+window.location.pathname;
var accessToken = null; //the access token is required to make any endpoint calls, http://instagram.com/developer/endpoints/
var authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) {
//the pop-up window size, change if you want
var popupWidth = 700,
popupHeight = 500,
popupLeft = (window.screen.width - popupWidth) / 2,
popupTop = (window.screen.height - popupHeight) / 2;
//the url needs to point to instagram_auth.php
var popup = window.open('instagram_auth.php', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+'');
popup.onload = function() {
//open authorize url in pop-up
if(window.location.hash.length == 0) {
popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token', '_self');
}
//an interval runs to get the access token from the pop-up
var interval = setInterval(function() {
try {
console.log(window.location);
//check if hash exists
if(popup.location.hash.length) {
//hash found, that includes the access token
clearInterval(interval);
accessToken = popup.location.hash.slice(14); //slice #access_token= from string
popup.close();
if(callback != undefined && typeof callback == 'function') callback();
}
}
catch(evt) {
//permission denied
console.log("error");
}
}, 100);
}
};
function login_callback() {
alert("You are successfully logged in! Access Token: "+accessToken);
}
function login() {
authenticateInstagram(
'16edb5c3bc05437594d69178f2aa646a', //instagram client ID
'localhost/facebook', //instagram redirect URI
login_callback //optional - a callback function
);
return false;
}
The code is ok, I think it is a problem with your app settings: Login to Instagram Developer, go to "Manage Client" and the "security" tab an disable "Implicit OAuth".

Posting facebook status

I'm trying to figure out how to use PhantomJS. I wrote the script below to try and automate posting a Facebook status. As far as I'm aware, the script isn't even logging in, which I'm unsure why. My code is below:
var page = require('webpage').create();
page.open('https://www.facebook.com/', function() {
page.includeJs("//code.jquery.com/jquery-1.11.0.min.js", function() {
page.evaluate(function() {
// Login
$('#email').val('email_here'); // Set email
$('#pass').val('password_here'); // Set PW
$('#u_0_4').click();
// Set status
$('#u_0_1p').val('123');
$('#u_0_1f').submit();
});
phantom.exit()
});
});
I'm not sure why the script won't work, or even to get some sort of error message output so I can figure out why my script isn't working.
Here is code for Loging in facebook i have written this in javascript it login's and takes a screen shot of your facebook home page..
var page = require('webpage').create();
var fillLoginInfo = function(){
var frm = document.getElementById("login_form");
frm.elements["email"].value = 'your fb email/username';
frm.elements["pass"].value = 'password';
frm.submit();
}
page.onLoadFinished = function(){
if(page.title == "Welcome to Facebook - Log In, Sign Up or Learn More"){
page.evaluate(fillLoginInfo);
return;
}
else
page.render('./screens/some.png');
console.log("completed");
phantom.exit();
}
page.open('https://www.facebook.com/');
Find this on Github: https://github.com/manishjo/Automation/blob/master/facebook_automation/fbScreenshot.js
Still trying to find out after login how to Post msg.
Thanks,
Manish Joshi

FB Connect dialogs don't close

When I click on my FB log in button the FB auth dialog pops up. After I enter my FB credentials the dialog redirects to a url like this:
https://www.facebook.com/dialog/permissions.request?wholeBunchOfQueryParameters
or, if I was already logged into FB, the popup dialog is:
https://www.facebook.com/dialog/oauth?wholeBunchOfQueryParameters
but those are blank dialogs that stay open. Once I close the dialog the callback happens but not until then. This is the behavior on IE and Chrome.
I did have this working fine and I think it stopped working when I got a new computer so maybe it is environmental. I thought it has worked since then but maybe not. I reverted to a version of my code that was working and it no longer works either so that further suggests that it is environmental but I don't know what it could be. I could be off in the weeds.
Also, one other bit of info, I'm developing locally so I'm using localhost:port. I did a ton of research on this issue and did see someone say to use 127.0.0.1 instead of localhost so I did try that as well but it didn't make a difference.
Any idea why the dialogs won't close?
<fb:login-button perms="email,user_checkins" onlogin="afterFacebookConnect();"
autologoutlink="false" ></fb:login-button>
<div id="fb-root" style="display:inline; margin-left:20px;"></div>
<script language="javascript" type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: 'myAppId',
status: true, cookie: false, xfbml: true
});
};
function afterFacebookConnect() {
FB.getLoginStatus(function (response) {
alert("Hi");
var access_token = FB.getAuthResponse()['accessToken'];
if (response.authResponse) {
window.location = "../Account/FacebookLogin?token=" +
access_token;
} else {
alert(FB.getAuthResponse);
}
});
};
function logout() {
FB.getLoginStatus(function (response) {
var access_token = FB.getAuthResponse()['accessToken'];
if (response.authResponse) {
window.location = "../Account/Logout";
} else {
// user clicked Cancel
}
});
};
$(document).ready(function () {
if (document.getElementById('fb-root') != undefined) {
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);
}
});
</script>
This is a known bug that has surfaced in the last few days (see https://developers.facebook.com/bugs/241915819261223).
The good news is one of FB's Engineers has just stated the following, so we should see this resolved shortly:
We have a fix for this issue and it will be pushed soon. Stay tuned.

Categories

Resources