Facebook JS SDK: Correct way to initialize the SDK - javascript

Below is how Facebook recommends adding their JS SDK to your source.
window.fbAsyncInit = function() {
FB.init({
appId : '{your-app-id}',
status : true,
xfbml : true
});
};
(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";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
If I understand correctly, the Second part of the code, creates a <script></script> node in the DOM and sets the source to //connect.facebook.net/en_US/all.js
Why does window.fbAsyncInit function come before that and not after? Won't the browser try to run it before it actually gets to the second part of the code where the SDK is actually loaded? Is it possible that all.js is loaded in the DOM only after FB.init() is called, thus generating an error?

Why does window.fbAsyncInit function come before that and not after?
You can write this code anywhere in you wish.
Won't the browser try to run it before it actually gets to the second part of the code where the SDK is actually loaded?
window.fbAsyncInit is triggered after the SDK is loaded asynchronously, so it doesn't matter where you write this- before/after or anywhere.
Is it possible that all.js is loaded in the DOM only after FB.init() is called, thus generating an error?
What error? Btw, all.js cannot be loaded after FB.init. It's the reverse process- FB can be initialized only after the SDK is loaded! Once the SDK is loaded it will automatically come inside- window.fbAsyncInit = function() {

Related

How to avoid Facebook xfbml.customerchat.js conflict with sdk.js?

I have two apps on my webisite
Customer Chat plugin (taken from Facebook Fan Page)
Facebook login app
Fist one loads
js.src = '//connect.facebook.net/en_EN/sdk/xfbml.customerchat.js';
Second one loads
js.src = "//connect.facebook.net/en_EN/all.js#xfbml=1&version=v3.3&appId=MYFACEBOOKID";
Both apps won't work together - if one work tne other dont.
So if Faecbook login SDK will load as first then Customer chat throw's that console notice:
The CustomerChat plugin is no longer part of the main Facebook SDK.
To continue using it please use the correct SDK URL,
meaning replace sdk.js with sdk/xfbml.customerchat.js.
For more details see https://developers.facebook.com/docs/messenger-platform/discovery/customer-chat-plugin/sdk
Otherwise if only Customer chat is loaded then
FB.login() called before FB.init().
occur...
Ideas?
That piece of code is from Customer Chat plugin (generated by FB in Fan Page settings).
I have added one part of FB.init from Facebook login plugin inside as below:
<script>
window.fbAsyncInit = function() {
FB.init({
xfbml : true,
version : 'v3.3'
});
};
// added part START
window.fbAsyncInit = function() {
FB.init({
appId : 'MYAPPID', // Facebook login
cookie : true,
xfbml : true,
version : 'v3.3'
});
};
// added part END
(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/lt_LT/sdk/xfbml.customerchat.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
Both plugins started to work.

Facebook Javascript SDK post to feed giving "An error occured. Please try later" error

I'm using the JS SDK to post something on the user's timeline. My website is hosted using site44 and so has a url of the type http://domainname.site44.com. This is the code I'm using:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '{*********}', // APP ID
channelURL : 'http://domainname.site44.com/channel.html',
xfbml : true,
version : 'v2.0'
});
};
(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 = "http://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function share(){
FB.ui({
method: 'feed',
name: 'something',
caption: 'something',
description: (
'something'
),
link: 'http://domainname.site44.com',
picture: 'imageLinkInsertedHere'
});
}
</script>
In the channel.html file I have this code:
<script src="http://connect.facebook.net/en_US/all.js"></script>
and I trigger the share() function when a user clicks on a button using javascript's onclick="share()".
I tested this on fbrell and it works perfectly. However when I use it on my site the pop up gives an error saying An error occurred. Please try later. I've gone through other similar questions on Stack Overflow and none of them helped. I also have the correct domain added in my APP settings. What am I doing wrong?
The appId must not include the curly braces {/}. Rest of the code seems fine.
But another thing that you should know is that the Feed Dialog is now deprecated. You should now use the modern Share Dialog instead. Here's the example for the same.

Like button not showing up

I have the following code to start facebook SDK on the site (warning, stripped some functions out, and removed namespaces because they don't add to this discussion):
var facebookAppId = "501843009849438";
var facebookEvents = (function(){
var facebookHasLoaded = false;
var asyncLoadFacebook = function() {
// exposed to window because it is called by facebook
window.fbAsyncInit = function() {
FB.init({
appId : facebookAppId, // App ID
channelUrl : '//'+location.host+'/nl/recommendations/facebook/channel.html', //Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// 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.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
facebookHasLoaded = true;
};
return {
enable: function() {
if (!facebookHasLoaded) {
jQuery('body').append('<div id="fb-root" />');
asyncLoadFacebook();
}
}
};
})();
// If there are no fb-like's found, we don't auto-start and you should manually load .enable().
jQuery(document).ready(function(){
if (jQuery('.fb-like').length !== 0) {
facebookEvents.enable();
}
});
This javascript is placed in a file that is loaded on every page of the site. Because we don't want to load the SDK on every page, the check has been added on 'document.ready'.
What have I done to try and fix it
I have placed breakpoints in Chrome, and it nicely gets into the asyncLoadFacebook function. I also get an iframe inside my div on a page. Tried developers.facebook.com. Also read a lot of fora around the interwebs. Double checked the appId via facebook graph, it is the right appId.
HTML for the like button
This is the div I use to show the like button:
<div class="fb-like" data-href="${canonicalURLEncoded}" data-send="false" data-layout="button_count" data-width="150" data-show-faces="false" data-font="verdana"></div>
The only thing "wrong" when loading pages is that I see a lot of error messages like:
Blocked a frame with origin "http://****************" from accessing a frame with origin "https://s-static.ak.facebook.com". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
But I never use http or https in the code when calling some script url (as you can see in the script sample). The pages with like buttons are in http. Plus, google plus gives the same logs in the console, but the plusone buttons just works like it should.
Inline is not possible
Unfortunaly I cannot just deploy and test around. Especially inline javascript (right after the body) is NOT an option. I really want the async version to just work..

Facebook Javascript SDK FB Undefined

When attempting to use the Facebook JS SDK, I keep running into the error FB undefined.
When I watch it through the JavaScript debugger on IE it runs through correctly during the page load, then at the end it is just undefined and no events that are subscribed to fire.
The goal: to make a page tab refresh the top most level page, to get past the fan gate.
Any ideas on what I am missing here?
Code:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function(){
FB.init({
appId : 'APP CODE INSERTED HERE',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'URL to Channel .ASPX'
});
// Additional initialization code here
FB.Event.subscribe('edge.create',
function(response){
top.location.href = 'Page to refreshed inserted here';
});
};
(function(d)
{
var js, id = 'facebook-jssdk';
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document)
);
</script>
Your JavaScript to load the SDK Asynchronously doesn't match what the Facebook SDK documentation currently shows. See below:
// 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));
Both blocks of JavaScript to load the SDK are very similar. Your JavaScript uses:
d.getElementsByTagName('head')[0].appendChild(js);
To load the SDK. The most current version as documented by FB uses:
ref = d.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(js, ref);
Your version adds the source reference to load the FB JavaScript by appending to the HEAD HTML tag. The most current version does this by finding the first SCRIPT reference and inserting the FB reference before that reference.
Perhaps your issue is caused by the subtle differences between these two methods.
One way to rule this out would be to temporarily hard code the loading of the FB JavaScript synchronously by placing the following HTML into your page's header:
<head>
<script type="text/javascript" src="http://connect.facebook.net/en_us/all.js"></script>
.
.
.
</head>

How to workaround 'FB is not defined'?

Sometimes I'm getting the "FB is not defined" issue when loading the http://connect.facebook.net/en_US/all.js
I've realized that the problem is because sometimes my website just doesn't load that file. So it gets nothing, and the object FB literally doesn't exist.
My solution is to prevent my users when this happens, so I've tried the following codes in JavaScript but none seems to work:
if (FB) {/*run the app*/} else {/*alert the user*/}
if (FB!==false) {/*run the app*/} else {/*alert the user*/}
if (FB!='undefined') {/*run the app*/} else {/*alert the user*/}
thanks for the answer!
I think you should solve the main issue instead, which solution is provided by Facebook (Loading the SDK Asynchronously):
You should insert it directly after the opening tag on each page you want to load it:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.1'
});
};
(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'));
</script>
From the documentation:
The Facebook SDK for JavaScript doesn't have any standalone files that
need to be downloaded or installed, instead you simply need to include
a short piece of regular JavaScript in your HTML that will
asynchronously load the SDK into your pages. The async load means
that it does not block loading other elements of your page.
UPDATE: using the latest code from the documentation.
Assuming FB is a variable containing the Facebook object, I'd try something like this:
if (typeof(FB) != 'undefined'
&& FB != null ) {
// run the app
} else {
// alert the user
}
In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!
As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.
I guess you missed to put semi-colon ; at the closing curly brace } of window.fbAsyncInit = function() { ... };
For people who still got this FB bug, I use this cheeky fix to this problem.
Instead of http://connect.facebook.net/en_US/all.js, I used HTTPS and changed it into https://connect.facebook.net/en_US/all.js
and it fixed my problem.
There is solution for you :)
You must run your script after window loaded
if you use jQuery, you can use simple way:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
status : true,
version : 'v2.5'
});
};
(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'));
</script>
<script>
$(window).load(function() {
var comment_callback = function(response) {
console.log("comment_callback");
console.log(response);
}
FB.Event.subscribe('comment.create', comment_callback);
FB.Event.subscribe('comment.remove', comment_callback);
});
</script>
You were very close with your original example. You could either use #jAndy's suggestion or:
if (typeof FB != 'undefined')
It's pretty strange for FB not to be loaded in your javascript if you have the script tag there correctly. Check that you don't have any javascript blockers, ad blockers, tracking blockers etc installed in your browser that are neutralizing your FB Connect code.
I had FB never being defined. Turned out that I was prototyping functions into the Object class called "merge" and another called "toArray".
Both of these screwed up Facebook, no error messages but it wouldn't load.
I changed the names of my prototypes, it works now. Hey, if Facebook is going to prototype Object, shouldn't I be allowed to prototype it?
FB recommends to add the async all.js include right after body, so that FB object get prepared when you use it in page.
You can also have artificial delay using setTimeout to make sure FB object is loaded. e.g.
<script>setTimeout(function(){
FB.Event.subscribe('edge.create',
function (response) {
alert('msg via fb');
});},2000);
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId :'your-app-id',
xfbml :true,
version :'v2.1'
});
};
(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'));
</script>
From the documentation: The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML tha
I had a similar issue and it turned out to be Adblocker Pro. Be sure to check that this or other blocking extensions have been disabled. I lost around 1hr 30 mins due to this. Feel like such a noob ;)
...
</head>
<body>
<!-- Load Facebook SDK for JavaScript -->
<div id="fb-root"></div>
<script type="text/javascript">
...
Check div id="fb-root" /div" !!! It's very important to run.

Categories

Resources