[javascript] How to add facebook share button on my website?

I have this code that suppose to work, but doesn't work. If this helps you in anyway that would be great.

<script src='http://connect.facebook.net/en_US/all.js'></script>
    <p><a onclick='postToFeed(); return false;'><img src="images/fb.png" /></a></p>
    <p id='msg'></p>

    <script> 
      FB.init({appId: "338334836292077", status: true, cookie: 

true});

      function postToFeed() {

        // calling the API ...
        var obj = {
          method: 'feed',
          redirect_uri:'https://www.facebook.com/cryswashington?fref=ts',
          link:'https://developers.facebook.com/docs/reference/dialogs/',
          picture: 'http://fbrell.com/f8.jpg',
          name: 'Facebook Dialogs',
          caption: 'Reference Documentation',
          description: 'Using Dialogs to interact with users.'
        };

        function callback(response) {

        document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
        }

        FB.ui(obj, callback);
      }

    </script>

I want to add facebook share button on my website, that should just post my website's content on the wall. who want to share it.

I have researched a lot but did not get anything. Pleas help me in this.

Thanks in advance.

The answer is


This Facebook page has a simple tool to create various share buttons.

For example, this is some output I got:

<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v8.0" nonce="dilSYGI6"></script>
<div class="fb-share-button" data-href="https://www.mocacleveland.org/exhibitions/lee-mingwei-you-are-not-stranger" data-layout="button" data-size="small">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.mocacleveland.org%2Fexhibitions%2Flee-mingwei-you-are-not-stranger&amp;src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a>
</div>

You can do this by using asynchronous Javascript SDK provided by facebook

Have a look at the following code

FB Javascript SDK initialization

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

Note: Remember to replace YOUR APP ID with your facebook AppId. If you don't have facebook AppId and you don't know how to create please check this

Add JQuery Library, I would preferred Google Library

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

Add share dialog box (You can customize this dialog box by setting up parameters

<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
</script>

Now finally add image button

<img src = "share_button.png" id = "share_button">

For more detailed kind of information. please click here


For Facebook share with an image without an API and using a # to deep link into a sub page, the trick was to share the image as picture=

The variable mainUrl would be http://yoururl.com/

var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);

var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);

var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);

var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;

// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
  var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
  return false;
});

// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
  var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
  return false;
});

Share Dialog without requiring Facebook login

You can Trigger a Share Dialog using the FB.ui function with the share method parameter to share a link. This dialog is available in the Facebook SDKs for JavaScript, iOS, and Android by performing a full redirect to a URL.

You can trigger this call:

FB.ui({
  method: 'share',
  href: 'https://developers.facebook.com/docs/', // Link to share
}, function(response){});

You can also include open graph meta tags on the page at this URL to customise the story that is shared back to Facebook.

Note that response.error_message will appear only if someone using your app has authenticated your app with Facebook Login.

Also you can directly share link with call by having Javascript Facebook SDK.

https://www.facebook.com/dialog/share&app_id=145634995501895&display=popup&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer

https://www.facebook.com/dialog/share&app_id={APP_ID}&display=popup&href={LINK_TO_SHARE}&redirect_uri={REDIRECT_AFTER_SHARE}
  • app_id => Your app's unique identifier. (Required.)

  • redirect_uri => The URL to redirect to after a person clicks a button on the dialog. Required when using URL redirection.

  • display => Determines how the dialog is rendered.

If you are using the URL redirect dialog implementation, then this will be a full page display, shown within Facebook.com. This display type is called page. If you are using one of our iOS or Android SDKs to invoke the dialog, this is automatically specified and chooses an appropriate display type for the device. If you are using the Facebook SDK for JavaScript, this will default to a modal iframe type for people logged into your app or async when using within a game on Facebook.com, and a popup window for everyone else. You can also force the popup or page types when using the Facebook SDK for JavaScript, if necessary. Mobile web apps will always default to the touch display type. share Parameters

  • href => The link attached to this post. Required when using method share. Include open graph meta tags in the page at this URL to customize the story that is shared.

For your own specific server or different pages & image button you could use something like this (PHP only)

<a href="http://www.facebook.com/sharer/sharer.php?u=http://'.$_SERVER['SERVER_NAME'].'" target="_blank"><img src="http://i.stack.imgur.com/rffGp.png" /></a>

I cannot share the snippet with this but you will get the idea...


You can read more about share button here on Facebook developers website

Working JSFIDDLE

Also take a look at custom Facebook Share button JSFIDDLE

Include Facebook JavaScript SDK code right after the opening <body> tag

<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";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

And place below code wherever you want to show Facebook Share button

<div class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-width="200" data-type="button_count"></div>

enter image description here

Check working JSFIDDLE


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to facebook

I am receiving warning in Facebook Application using PHP SDK React-Native: Application has not been registered error Can't Load URL: The domain of this URL isn't included in the app's domains Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Open Facebook Page in Facebook App (if installed) on Android App not setup: This app is still in development mode IOS - How to segue programmatically using swift Get ALL User Friends Using Facebook Graph API - Android

Examples related to facebook-javascript-sdk

Chrome violation : [Violation] Handler took 83ms of runtime "Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query How to add facebook share button on my website? Given URL is not permitted by the application configuration How to get access token from FB.login method in javascript SDK Facebook API error 191 Facebook Javascript SDK Problem: "FB is not defined"

Examples related to share

Hyper-V: Create shared folder between host and guest with internal network How to mount host volumes into docker containers in Dockerfile during build custom facebook share button Sharing link on WhatsApp from mobile website (not application) for Android How to access shared folder without giving username and password How to activate "Share" button in android app? How to add facebook share button on my website? Using global variables between files? How to make a custom LinkedIn share button How to use "Share image using" sharing Intent to share images in android?

Examples related to facebook-social-plugins

Responsive width Facebook Page Plugin How to add facebook share button on my website? Given URL is not permitted by the application configuration