How to change open graph meta tags to share custom content on social media?

家住魔仙堡 提交于 2019-12-04 20:48:04

This is an excellent question. I've been through this before and i know how awful this can be.

So, first you need to registrate a facebook App, into developers.facebook.com, to have you own app Secret and App ID.

Second, you need to init Facebook Javascript SDK

window.fbAsyncInit = function() {
    FB.init({
        appId: YOUR_APP_ID,
        channelUrl: YOUR_CHANNEL_URL,
        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'));

Third you need to create a function or a method that dynamically call FB UI (which is the dialog box that will appear ass the user click in the share button) with your image data.

function shareMyImage(data) {
    FB.ui(

      {
        method: 'feed',
        name: 'Facebook Dialogs',
        link: data.link,
        picture: data.image,
        caption: data.caption,
        description: data.description
      },
      function(response) {
        if (response && response.post_id) {
          alert('Post was published.');
        } else {
          alert('Post was not published.');
        }
      }
    );
} 

And last, but not least, you need to call your function

shareMyImage({
    link: 'http://link-to-your-page.com',
    image: 'http://link-to-your-page.com/your-image.jpg',
    caption: 'Reference info'
    description: 'Description to your image'
});

Dynamic Structure

Obviously, the above 'share info' have to be dynamic as well, so you can use data attributes to pass this info easily

<span class="button--share" data-link="THE LINK" data-image="THE IMAGE" data-caption="THE CAPTION" data-description="THE DESCRIPTION">Share</span>

So, you can use jQuery .data() to parse the info and directly run your method.

$('.button--share').on('click', function(){
    var data = $(this).data();
    shareMyImage(data);
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!