Create custom Facebook share with Javascript - javascript

I'm trying to make facebook share button with javascript.
Here is my code:
<script>
window.fbAsyncInit = function() {
FB.init({
appId: 'my app id',
status: true,
cookie: true,
xfbml: true
});
};
(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));
function postToFeed(title, desc, url, image) {
var obj = {
method: 'feed',
link: url,
picture: image,
name: title,
description: desc
};
function callback(response) {}
FB.ui(obj, callback);
}
var fbShareBtn = document.querySelector('.fb_share'); //my problem start
fbShareBtn.addEventListener('click', function(e) {
e.preventDefault();
var title = fbShareBtn.getAttribute('data-title'),
desc = fbShareBtn.getAttribute('data-desc'),
url = fbShareBtn.getAttribute('href'),
image = fbShareBtn.getAttribute('data-image');
postToFeed(title, desc, url, image);
return false;
});
Here is the HTML:
<div id="fb-root"></div>
Facebook
The problem is the share button only work for post number 1 or top post. I think it's because the javascript no catch the id
Any answer?

You can also get the code from here : https://www.addthis.com/dashboard#gallery/

Related

Facebook Share dialog just refreshes page

I have used the below code to implement the Facebook sharing dialog. VERY occasionally, it pops open a share dialog. 97% of the time, it just refreshes the page.
Any help is appreciated.
Share
<script type="text/javascript">
window.fbAsyncInit = function(){
FB.init({
appId: 'myappID', status: true, cookie: true, xfbml: true });
};
(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));
function postToFeed(title, desc, url, image){
var obj = {method: 'feed',link: url, picture: 'http://www.url.com/images/'+image,name: title,description: desc};
function callback(response){}
FB.ui(obj, callback);
}
$('.btnShare').click(function(){
elem = $(this);
postToFeed(elem.data('title'), elem.data('desc'), elem.prop('href'), elem.data('image'));
return false;
});
</script>

Fb.api posting undefined on as wall post

I want to post the value of an HTML id as the message on my Facebook wall. Posting to Facebook works but FB ends up writing undefined as the value pass in for message:. I am using var word = document.getElementById("fb-root").value; to get the value but fb.api is turning the value into undefined.
Please see code below:
<html>
<head>
<title>My Facebook Login Page</title>
<script type="text/javascript">
function postToWall() {
var word = document.getElementById("fb-root").value;
var params = {};
params['message'] = word;
params['name'] = 'test';
params['description'] = 'test';
params['link'] = 'asas.com';
params['picture'] = 'http://3.bp.blogspot.com/--jbgq-gytJQ/URaJHK_93LI/AAAAAAAAAF0/SkyoK7H3r7U/s1600/Simple+Apple.png';
params['caption'] = 'test';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert(word);
}
});
}
</script>
<div id="fb-root">test</div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'test',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
};
// 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));
</script>
</head>
<body>
<div id="fb-root">tests</div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId:<fbapp-id>, cookie:true,
status:true, xfbml:true
});
</script>
<fb:login-button perms="publish_stream">Login with Facebook</fb:login-button>
Post To Wall
</body>
</html>
After checking the code (it's messed up) you need to pay attention to these points,
Everything is duplicated
In HTML, you can't have more than one element with an id, here you have 2 elements with id fb-root
<div id="fb-root">test</div>
You're loading the JS-SDK 2 times, once in asynchronous;
// 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));
and other in synchronous (using <script>)
<script src="http://connect.facebook.net/en_US/all.js"></script>
You calling FB.init() twice
You put one of fb-root element in head tag, it's a sin in HTML ;)
<div id="fb-root"></div> is removed from the DOM when you instance the Facebook app, it's like a dummy element but important for Facebook, not you or me, you should always leave it and not use it, instead create a new element with a different id like myWord
<div id="myWord">my word</div> though div are not inline element which makes a bad practice.
Here's your cleaned code;
<html>
<head>
<title>My Facebook Login Page</title>
<script type="text/javascript">
function postToWall() {
var word = document.getElementById("myWord").value;
var params = {};
params['message'] = word;
params['name'] = 'test';
params['description'] = 'test';
params['link'] = 'asas.com';
params['picture'] = 'http://3.bp.blogspot.com/--jbgq-gytJQ/URaJHK_93LI/AAAAAAAAAF0/SkyoK7H3r7U/s1600/Simple+Apple.png';
params['caption'] = 'test';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert(word);
}
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '{App_id}',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
};
// 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));
</script>
</head>
<body>
<div id="fb-root"></div>
<fb:login-button perms="publish_stream">Login with Facebook</fb:login-button>
Post To Wall
</body>
</html>
document.getElementById("myWord").value
needs to be changed to
document.getElementById("myWord").innerHTML

FBe is not a function even though it is defined

<script>
var userId = '1';
var appId = 'MYAPPID';
var appHost = 'https://localhost:44300/';
// Api holder
FBe = {};
// FB JS SDK
window.fbAsyncInit = function () {
FBe = FB;
FBe.init({
appId: appId,
status: true,
cookie: true,
xfbml: true,
frictionlessRequests: true
});
};
(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>
<script>
// Test
function fbTest() {
FBe.api('/me', function (response) {
alert('Your name is ' + response.name);
});
}
fbTest();
</script>
my code above gives me this:
TypeError: FBe.api is not a function
Why am i getting this error?
How can i fix it?
You are calling fbTest() too early. You have to wait until after window.fbAsyncInit has been called. The FB API is not yet loaded.
Because you are loading the FB API asynchronously, you can't use it until after window.fbAsyncInit has been called. Any use of the FB API upon page load should be called from window.fbAsyncInit.

Access denied error in Facebook js code

For the past week or so, I have been getting sporadic javascript errors when using Facebook's js sdk code.
This is the error:
Here's the line of code:
JavaScript code from Facebook's site:
/*1345677565,173217057*/
if (window.CavalryLogger) { CavalryLogger.start_js(["p0usZ"]); }
if(!Array.isArray)Array.isArray=function(a){return Object.prototype.toString.call(a)=='[object Array]';};
if(!Array.prototype.map)Array.prototype.map=function(a,b){if(typeof a!='function')throw new TypeError();var c,d=this.length,e=new Array(d);for(c=0;c<d;++c)if(c in this)e[c]=a.call(b,this[c],c,this);return e;};if(!Array.prototype.forEach)Array.prototype.forEach=function(a,b){this.map(a,b);};if(!Array.prototype.filter)Array.prototype.filter=function(a,b){if(typeof a!='function')throw new TypeError();var c,d,e=this.length,f=[];for(c=0;c<e;++c)if(c in this){d=this[c];if(a.call(b,d,c,this))f.push(d);}return f;};if(!Array.prototype.every)Array.prototype.every=function(a,b){if(typeof a!='function')throw new TypeError();var c=new Object(this),d=c.length;for(var e=0;e<d;e++)if(e in c)if(!a.call(b,c[e],e,c))return false;return true;};if(!Array.prototype.some)Array.prototype.some=function(a,b){if(typeof a!='function')throw new TypeError();var c=new Object(this),d=c.length;for(var e=0;e<d;e++)if(e in c)if(a.call(b,c[e],e,c))return true;return false;};if(!Array.prototype.indexOf)Array.prototype.indexOf=function(a,b){var c=this.length;b|=0;if(b<0)b+=c;for(;b<c;b++)if(b in this&&this[b]===a)return b;return -1;};
if(!Date.now)Date.now=function(){return new Date().getTime();};
window.__DEV__=window.__DEV__||0;
My code:
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'xxxx',
status: true,
cookie: true,
xfbml: true
});
};
// 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));
</script>
My code does not do anything special. It's copied from Facebook's documentation.
Any ideas what's going on and how I can address the issue?

Facebook JS SDK returns no results

I ran an example copied from:
http://developers.facebook.com/docs/reference/javascript/
http://developers.facebook.com/docs/reference/javascript/FB.api/
(I only changed my APP_ID)
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/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
});
FB.api('/platform/posts', { limit: 3 }, function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
};
// 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));
</script>
Nothing shows in the browser. There is no JavaScript errors in console (Opera 11). Why is it not working?
I had the same issue and realized that the example is not parsing the response correctly. The object has a property data which is actually the Array to be parsed.
Another point is that you need a token to do this operation. So your code should be:
<div id="fb-root"></div>
<script>
var fbToken; // Highly recommended to make it global
window.fbAsyncInit = function()
{
FB.init({
appId : 'MY_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/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
});
FB.login(function(response)
{
if (response.authResponse)
{
fbToken = response.authResponse.accessToken; // Save it for another requests
FB.api('/platform/posts', {limit:3}, function(response){
for (var i=0, l=response.data.length; i<l; i++)
{
var post = response.data[i];
if (post.message)
{
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name)
{
alert('Attachment: ' + post.attachment.name);
}
}
});
} else {
// User did not accept oAuth
}
});
}
// 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));
</script>
It looks like you're not logged in. You need to authenticate the user to get an oauth token in place first before you can run this part of the code:
FB.api('/platform/posts', { limit: 3 }, function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
See: http://developers.facebook.com/docs/reference/javascript/FB.login/

Categories