Facebook Javascript SDK Not Initializing - facebook-javascript-sdk

I'm trying to incorporate Facebook sharing into the website I'm building. I'm following FB's guide for including their Javascript SDK (and copy/pasting their code inside a script tag directly following the body tag) but for some reason it isn't working. In the following code "running" is successfully printed but the "Initialized" never prints and the shareFacebook function is never successfully initialized. Does anyone know why this is?
console.log("Running init script");
window.fbAsyncInit = function() {
FB.init({
appId : '444853392519445',
xfbml : true,
version : 'v2.8'
});
FB.AppEvents.logPageView();
function shareFacebook() {
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function (response) {
});
console.log("Inside shareFacebook");
}
console.log("Initialized");
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);

I think, that I had the same Problem with Facebook SDK. Can you test with
js.src = "//connect.facebook.net/en_US/all.js";
and remove also version : 'v2.8'.

Related

Vue2 Router vs Facebook Javascript SDK: Redirect URI

I have a vue2 single-page-app. In an vue component, I try to use Facebook Javascript SDK to authenticate and use Graph API.
In a method, I use this code to connect to Facebook
window.fbAsyncInit = function () {
FB.init({
appId: 'xxx',
cookie: true,
xfbml: true,
version: 'v2.10'
});
console.log(FB);
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
};
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
//js.src = "//connect.facebook.net/de_DE/sdk.js";
js.src = "https://connect.facebook.net/de_DE/sdk/debug.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
When the app executes the method FB.getLoginStatus, I get the error message “URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings.”.
I know that I have to go to the settings of my facebook app and enter the redirect url into OAuth Redirect URIs.
My problem is, I have done this. The callback url is https://localhost/myapp/public/api/facebook/callback. So I guess I'm too stupid to find out the correct callback url... Any ideas how to find out this one?
I solved the problem using the vue router history mode.
In my router js file, I added this line:
const router = new VueRouter({
mode: 'history', // that did the trick
routes: [ ... ]
})
There may be a better solution, but it works for me...

FB.NativeExtensions.onready only works when the page is rendered in a WebView of the native Facebook app

Facebook SDK throws following console error:
FB.NativeExtensions.onready only works when the page is rendered in a WebView of the native Facebook app. Test if this is the case calling FB.UA.nativeApp()
sdk.js:57
Has anyone encountered this?
I created this simple fiddle and it shows the error even by just loading FB SDK.
// Load the SDK Asynchronously
(function(d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
fiddle

HotTowel SPA with Facebook SDK

I've started a new Visual Studio 2012 Express Web project using the HotTowel SPA template. I'm not sure where I should be placing the code to load the Facebook SDK within the HotTowel structure?
I've tried main.js, and shell.js but I can't seem to get the sdk to load. Facebook says to put the below code to load the sdk asynchronously
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '577148235642429', // App ID from the app dashboard
channelUrl: '//http://localhost:58585/channel.html', // Channel file for x-domain comms
status: true, // Check Facebook Login status
xfbml: true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all/debug.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Create a module in a file called facebooksdk.js that contains this code. Then "require" the code in the boot sequence, if you want it to load right away.
It is not easy to use to use Facebook SDK with Durandal.
Facebook offers instructions how to set it up with require. But sounds like that method is not supported in Durandal.
I made my dirty version by wrapping global FB object with vm supporting knockout. You could easily use that and bind to any properties like users name.
Include that facebook.js from shell.js to make sure it is loaded when app starts.
Here is my facebook.js:
define(['services/logger'], function (logger) {
var vm = {
facebook: null,
initialized: ko.observable(false),
name: ko.observable(""),
picturesrc: ko.observable(""),
login: login,
logout: logout
};
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_UK/all.js', function () {
window.fbAsyncInit = function () {
vm.facebook = FB;
vm.facebook.init({
appId: '160000000000499',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
vm.initialized(true);
vm.facebook.getLoginStatus(updateLoginStatus);
vm.facebook.Event.subscribe('auth.statusChange', updateLoginStatus);
};
});
return vm;
function login() {
vm.facebook.login( function(response) {
//Handled in auth.statusChange
} , { scope: 'email' });
}
function logout() {
vm.facebook.logout( function (response) {
vm.picturesrc("");
vm.name("");
});
}
function updateLoginStatus(response) {
if (response.authResponse) {
logger.log("Authenticated to Facebook succesfully");
vm.facebook.api('/me', function (response2) {
vm.picturesrc('src="https://graph.facebook.com/' +
+response2.id + '/picture"');
vm.name(response2.name);
});
} else {
logger.log("Not authenticated to Facebook");
vm.picturesrc("");
vm.name("");
}
}
});
I have not tested my code properly. But atleast logging in and fetching name worked fine in Chrome.
Remember change appId and update proper domain at developers.facebook.com.

Facebook connect: How the javascript part works?

Actually, I am making a simple page in Symfony2.2. I've got the following codes in a twig template:
<!-- facebook link -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=297720976910223";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-login-button" data-show-faces="true" data-width="200" data-max-rows="1"></div>
<!-- end facebook link-->
They successfully do the following:
display a facebook login button on my page.
when I click on the button, I can enter my Facebook account.
I get my Facebook name displayed on my page.
Now what I wish to do is: After having entered a valid Facebook account on the Facebook popup, once I get back on my page, I can alert somthing. For example something like:
function after_click() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("Facebook user is connected");
}
});
..The problem is that I don't exactly how it works. I have tried several options in my codes and searched the net, but in vain.
Any one could explain me the principles for the above and guide me through?
(PS: My final objective is to replace the 'alert' code by a code which redirects the user to another page.)
Thank you alots.
#Thomas, thank you for your answer.. But I really don't understand why the following gives me an alert only when the btnTest is clicked (alert="You clicked on me for a test.."); other alerts are never displayed:
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '297720976910223', // App ID from the App Dashboard
status : true, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true // parse XFBML tags on this page?
});
// Additional initialization code such as adding Event Listeners goes here
FB.Event.subscribe('auth.login', function(response) {
alert("test connection");
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
alert("connected");
} else if (response.status === 'not_authorized') {
// not_authorized
alert("not authorized");
} else {
// not_logged_in
alert("not logged in");
}
}, true);
};
function testme()
{
alert("You clicked on me for a test..");
FB.getLoginStatus(function(response) {
alert("xxx_");
if (response.status === 'connected') {
// connected
alert("connected");
} else if (response.status === 'not_authorized') {
// not_authorized
alert("not authorized");
} else {
// not_logged_in
alert("not logged in");
}
});
}
// Load the SDK's source Asynchronously
// Note that the debug version is being actively developed and might
// contain some type checks that are overly strict.
// Please report such bugs using the bugs tool.
(function(d, debug){
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" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
</script>
<fb:login-button onlogin="testme()" autologoutlink='true' perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
<!-- Just for testing purposes-->
<button type="button" name="btnTest" onclick="testme()">Test</button>
<div class="fb-login-button" data-show-faces="true" onlogin="testme()" data-width="200" data-max-rows="1"></div>
</body>
</html>
PS: On facebook dev website its written:
Prerequisites:
You'll need somewhere that lets you host HTML files online. If you haven't got one, you can get set up quickly at no cost with Heroku.
I'm testing that file on my PC; does that make a difference..?
The function FB.getLoginStatus only tells you, whether the user is authenticated with your application, not if he just logged in.
You can register a listener on login status change to connected:
FB.Event.subscribe('auth.login', function(response) {
// handle the login
});
More info on FB JavaScript SDK Events.

Exposing variables from PhantomJS call to injectJS

I've followed examples for injecting jQuery from the getting started page and that works just fine. I have a local copy of jQuery in the same directory, and do something like...
if(page.injectJs('jquery.min.js')) {
page.evaluate(function(){
//Use jQuery or $
}
}
When I try to inject my own script(s), none of the functions are available to me. Say I have a script called myScript.js that just has
function doSomething() {
// doing something...
}
I cannot then use doSomething like...
if(page.injectJs('myScript.js')) {
console.log('myScript injected... I think');
page.evaluate(function() {
doSomething();
});
} else {
console.log('Failed to inject myScript');
}
I've tried
window.doSomething = function() {};
and
document.doSomething = function() {};
as well with no luck, as well as trying to call them with window.doSomething() or document.doSomething() in the subsequent page.evaluate().
The following works for me, maybe some other part of your app logic is wrong:
inject.coffee
page = require('webpage').create()
page.onConsoleMessage = (msg) -> console.log msg
page.open "http://www.phantomjs.org", (status) ->
if status is "success"
page.includeJs "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", ->
if page.injectJs "do.js"
page.evaluate ->
title = echoAndReturnTitle('hello')
console.log title
phantom.exit()
do.coffee:
window.echoAndReturnTitle = (arg) ->
console.log "echoing '#{arg}'"
console.log $(".explanation").text()
return document.title
Result:
> phantomjs inject.coffee
echoing 'hello'
PhantomJS is a headless WebKit with JavaScript API.
It has fast and native support for various web standards:
DOM handling, CSS selector, JSON, Canvas, and SVG.
PhantomJS is created by Ariya Hidayat.
PhantomJS: Headless WebKit with JavaScript API
or if you prefer JavaScript (they're auto-generated and a little ugly):
`inject.js':
// Generated by CoffeeScript 1.3.1
(function() {
var page;
page = require('webpage').create();
page.onConsoleMessage = function(msg) {
return console.log(msg);
};
page.open("http://www.phantomjs.org", function(status) {
if (status === "success") {
return page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", function() {
if (page.injectJs("do.js")) {
page.evaluate(function() {
var title;
title = echoAndReturnTitle('hello');
return console.log(title);
});
return phantom.exit();
}
});
}
});
}).call(this);
do.js:
// Generated by CoffeeScript 1.3.1
(function() {
window.echoAndReturnTitle = function(arg) {
console.log("echoing '" + arg + "'");
console.log($(".explanation").text());
return document.title;
};
}).call(this);