Dynamically change Facebook open graph meta data with JavaScript Share different text and images for the same url

Scroll this

This article is updated to reflect changes in the Facebook API as of July 17, 2017. and for API version 2.9+ .

This article is updated again on 27.06.2018. in order to fix small image size problem.
Thanks to all followers who reported this problem. It took some experimenting, but the solution is simple, just replace action_type: 'og.shares' with action_type: 'og.likes'. The small downside of this method is the sentence “John Doe likes an object on drib” which appears near the top of the share dialog and on the top of shared content on the user wall (see the images in this article).

Requirements

Basic knowledge of JavaScript and familiarity with Facebook open graph (og ) meta data is required. It is assumed that you have, or know how to obtain Facebook application id (if not, please checkout: developers.facebook.com/docs/apps/register ).

Introduction

In most situation Facebook open graph (og) meta tags will be filled while a page is being generated – before it is served to the browser. But there are situation where you want to change data to be shared dynamically with JavaScript, after the page has been served to the browser.

For example, you are creating a quiz and you want to enable the players to share their result on the Facebook, while at the same time linking the shared content to the beginning of the quiz – so that player’s friends could start playing the quiz right away.

One way to accomplish this is to use JavaScript to change data to be shared (title, description and image) while leaving the original quiz url unchanged. Actually, you want or need possibility to share different text and images for the same url.

Implementation

The quiz might have this og meta data tags:

But after the quiz has finished you want the player (lets call him George L.) to share something like this:

title: “George L. is the Yoda of the Star Trek!”
description: “George L. is the champion of the Star Trek geekhood – and nobody can beat him. Or … ? Click to play and prove to the George L. that you are as good as him!”
image: Some custom image to celebrate the player success.

Add this JavaScript somewhere between <head></head> to include Facebook JavaScript SDK:

Note: Enter your appId instead of 124285848214697 .

To display share dialogue with dynamically overridden title, description and image use this js code (action_type: ‘og.shares’ was replaced by action_type: ‘og.likes’):

To see the code in the action follow this link: quiz.html (feel free to view the source or scroll to the end of the article).

When you share this link: drib.tech/fbsharetest/quiz.html default og:meta data will be displayed:

 

If you answer correctly this data will be displayed (although we are sharing the same url as above):

If your answer is wrong, this data will be displayed (although we are sharing the same url as above):

Note: When displayed in the dialogue it seems that image size is not correct, (note the white border on the right). But when shared on the wall – everything is fine:

Deprecated

Old way to override og:meta data stopped working on July 17, 2017. But fortunately it is simple to replace this:

with the new API call as described above. For more info check: developers.facebook.com/docs/sharing/reference/feed-dialog .

Full example

(action_type: ‘og.shares’ was replaced by action_type: ‘og.likes’)

Or view source of this working example: quiz.html.

References:

134 Comments

  1. Thank you for shareOverrideOGMeta function. This save my life!!!

    • Hi Brian, thank you for the feedback. I am glad that you found the article useful. Blogs and stack overflow saved my life many times too. πŸ™‚

  2. This works great, thanks. But how can I keep the post from saying [My Name] shared an object. I’d like it to say shared an “article” or whatever the object type is.

    Thanks

    • Hi Aaron, unfortunately I didn’t find a way how to do it. I suspect it is not possible, but since this feature is not well documented, one can’t be sure 100%. If you find the solution please let us know. Thank you.

    • Wondering the same. Please let us know if you find any solution to this.

  3. Thank you for an almost perfect method. My post shows a small square image on the left side and the text is to the right of the image. How do I get the picture in full width?

    • Hi, this is the problem which I also experienced and it is addressed in the blog post. The white rectangle on the right side of the image shows while sharing, but once shared on the user wall it is in full width.

      • Hi, I tried applying this method as well and with the same concern. It did look well(full width image) on users wall on desktop and in android Facebook app. When checking on IOS devices(facebook site in mobile browser view as well), seems that it reverts to left image and right content display. Do you have any workaround for this? Or was I just missing something. Thanks!

        • Hi, unfortunately I don’t have access to the ios device. Maybe some of the readers can help?

    • Hi, are you sure that the image is large enough and in the correct proportion?
      The image should be at least 1200 Γ— 630 px. And this is also the correct proportion.

    • Hi, I believe that the problem is fixed now and the article is updated.

    • Hi Manish,
      Thank you for the feedback. I am glad that this blog post was useful. πŸ™‚

    • Thank you for the comment! I am glad that this post was useful! πŸ™‚

  4. Just a heads up, facebook has said that his method, specifically action_type: ‘og.shares’ and ‘og:image’ override have been deprecated. Don’t count on this to work consistently going forward.

    • Hi, yes, I am aware of that. Also in this post at the end is the solution which was also deprecated. But for now – it works! When it stops we will see what will be the next workaround.

  5. Thanks, for this solution.
    but, I want to change just description other content should remain as it set in meta property (like, “”). is there any way?

    • Hi. Did you try to leave out the other fields you don’t want to be changed? Or just fill them with your default values?

  6. Hello,

    I have an issue when I click the share the dialog pops up multiple times, any solution for this?

  7. This works great, thanks. But why “Share on your timeline” options is not included in share dialog?

    • Thanks! I don’t know. This is improvised solution until FB breaks it again, as they did the solution before that one.

  8. Hi, I have a catalog page where i am showing a list of cars based on user search. Each car has its own image. There is a details page which takes url like DetailsPage.aspx?carid=335 and shows the details of car along its image. My requirement is that i want a facebook share button on the catalog page against each car. If there are 10 search results, there will be 10 share buttons one for each car. The share dialog should display the image of car being shared. My js code is

    $.ajax(
    {
    url: ‘//connect.facebook.net/en_US/sdk.js’,
    dataType: ‘script’,
    cache: true,
    success: function (script, textStatus, jqXHR)
    {
    FB.init(
    {
    appId: ‘829751380567168’,
    xfbml: true,
    version: ‘v2.11’
    }
    );
    }
    });
    and meta tags on the details page are :

    Can someone guide me how to share image of each car on FB Share dialog.

    • Hi! From what I understand, I think you don’t need the solution from this post. Since each of your cards have a unique landing page, can you just share that link, and FB should be able to get the data from card unique landing page og: meta data. Solution from this post is useful if you want to share same page (url) with different data (image description).

  9. This is super helpful! Thank you so much for taking the time to look into this. I was wondering, have you ever been able to replicate this for Twitter and the Twitter card? I’d love to be able to do the same thing for them, as well.

    • Hi! Thanks. No, I don’t have any experience with the twitter sharing.

  10. i have problem, when i generate new image and set ‘og:image’ .
    the new image not appear.
    i need help

  11. Thanks .. This code work for me

    sir i want the Post id after the post how to get because in response it return blank string

    Thanks

  12. Hi,
    Really this is wonderful, Great Job.
    And i face one issue.
    If Anybody found the solution for replacing object with link
    In the above way time line shows “Rio shared an object on testApp.”
    But other website share display “Rio shared a link.”
    plz help me

    • Hi! Thank you. But I don’t know the solution to this problem. πŸ™

    • Hi,
      Sorry, I didn’t experience your problem. Popup from the demo in this post closes after publishing.

  13. If I use “share_open_graph” I’m not able to share to the page I manage. Any options I’m missing?

      • The share image is smaller and to the left when it is one of the custom images. When you click “share with original og:meta data” the image is the full width. It seems with some recent changes from FB you no longer can override the full size image perhaps.

        • Hi Daniel,
          Rob also reported this problem, but I am unable to replicate it. For me it is still working correctly.
          Facebook is known to test different “features” or fixes partially – some users will get the features sooner and some later. So, since I can’t replicate the problem – I can’t fix it. Sorry. πŸ™

        • Hi, finally I managed to reproduce the small image problem – but for now I didn’t find the solution yet. πŸ™

        • Hi, I believe that the problem is fixed now and the article is updated. Can you please test is it working for you now?

  14. In my case og meta tags are not changing dynamically.Whenever i click on share button, it shares the same image,description,title.

    • Hi Mohit! Does this example works in your browser: http://drib.tech/fbsharetest/quiz.html .
      If so, view the source and try to replicate the solution. If not please tell us in which browser and OS you are having the problems.
      Also, try to make simple test case independent of your main web project – that might also help you to debug the problem since there is much less variables that can influence the outcome.

  15. this is not working for me
    http://drib.tech/fbsharetest/quiz.htm
    and also when I placed code to my site I am getting error
    (Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.)

    but all urls is in facebook and whitelisted

  16. Thanks for this! I got it to work but have a problem with how its posting. See screenshot here https://imgur.com/o8qkzfY
    Basically its showing image on the left and text on the right. Did it for your example and the current project I’m working on now too. I’m on PC and its very strange cause 2 other team members also on PC see it with the full width image. I’ve tried setting ‘og:image:width’: ‘1200’, ‘og:image:height’: ‘630’ but it doesn’t do anything… Any help?

    • But in your example when I click “Share with original og:meta data” it displays full width. Strange…

    • Hi Rob,
      I saw your screenshot, but I can’t replicate that. When I try to share it shows the the big picture. It has some white space on the right, but then, after it is shared, on the wall it is full width.
      Sorry I don’t know what could be a problem. πŸ™

  17. Drib, thanks a lot for that !
    I was reading this article a few days ago and everything worked fine. Today, when trying to implement it, I found out that something weird is happening with the images in the share dialog. They are sometimes shrinked by Facebook without reason. This happens on your quiz.htm page too. The funny story is that it seems this behaviour is linked to your FB account. When I try with my main FB account, everything is fine. When I switch to my test FB account, a square image is used.
    Anyone else is experiencing this ?

    • Hi Rodi,
      Yes, some people also experienced this. (It is in the comments.) Unfortunately I was unable to reproduce this problem. My guess is that facebook is partially changing existing functionality and that change is still not propagated to all users. For now we can hope that somebody else who is experiencing this problem will find a way to fix it, or that I will be able to reproduce it and hopefully fix it.

  18. Hi! Thanks, it works fine!
    But maybe you know how to override ‘caption: overrideCaption,’
    Seems like they do not provide new properties in Open Graph for this?

  19. About the shrinking of images, according to something I found on stackoverflow (and according to facebook as well), the images of the apps with the category of games should be 600 x 600 px. So I think facebook automatically shrinks the images for those with the category of games. When I changed the category of my app to education, the images are now shown in large mode, even those I already posted.

    source: https://stackoverflow.com/questions/45091741/fb-ui-with-share-open-graph-method-displays-small-image-only

  20. PS: Thank you very much for this post. This helped me a lot.

  21. Hi Drib,

    I copied your working code (from view source), changed the APP ID but I’m also getting this error:

    (Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.)

    Yes, APP ID is valid and I listed the domain as required by Facebook

    • Hi Keme, it is hard to guess what might be a problem. The listed domains are entered without http:// or https:// ? Do you have any facebook alerts for that app?

  22. Hi! I am having a problem regarding the shared object. The image is not displaying. It’s only a white box.

    • Hi. Sorry I can’t reproduce this problem. Maybe you can provide more info, also asking the question on stackoverflow is an good idea because there is much more visitors then here.

  23. Thank you very much, for your detailed working code.

    Any idea how I can do the same for WhatsApp share buttons to have different images on the same web page

    • Hi Ofer, Thank you for your comment. No, I don’t have any previous experience with WhatsApp share buttons.

  24. Thanks for your example. I tried it on a project and copied your code, but i keep getting the class “hidden_elem” on description in the share window. Can’t find a solution. Do you have a suggestion?

    • Thanks, but unfortunately I didn’t came across this problem before. Sorry. πŸ™

      • If I use action_type: ‘og.shares’ instead of action_type: ‘og.likes’ the description appears. The layout is a little different though, but i can live with that :).
        Thanks again!

  25. Thanks for the article. It was very useful!
    I had the same problem with the size of the override image.
    The change trick ‘og:shares’ for ‘og:likes’, it did not work for me.
    But I have solved it by adding the parameter: ‘og:updated_time’: new Date().toISOString().

    • Thank you for the feedback and the advice. I will included in the article if you don’t mind. Thanks! πŸ™‚

  26. Hi, thanks for the article, it was really helpful. Is there a way to make it available for sharing also on facebook messenger?

  27. getting this error message from facebook
    “Object Missing a Required Value: Object at URL ” of type ‘object’ is invalid because a required property ‘og:title’ of type ‘string’ was not provided.”

    How do i fix it

  28. Hi there. Thanks for this code. I have set it up at http://meta-update.socialinfluenza.com/share-fb. I have created an app in FB and it is live. I added my FB app ID in both required sections of your code, but I still get errors. 1) When I do the quiz and submit my answer, I get “The parameter app_id is required”. 2) When I click “Share with original og:meta data”, I get “Invalid App ID: The provided app ID does not look like a valid app ID.” I am using the FB app ID provided by them. Any ideas on howto fix this? Thanks.

    • Hi Ted, I think your other js are affecting my example. Specifically this one: http://meta-update.socialinfluenza.com/js/common.js . It also calls fbAsyncInit but without app id and with api version v2.2, while you are using v3.0 for my example.
      And if you take a look of the url of your share dialog you will notice url: “https://www.facebook.com/v2.2/dialog/share?app_id=&channel_url=http” containing v2.2 and not v3.0 -> which means the common.js is overriding example js.
      So try to remove common.js and also check your other js that you are including in the page.

  29. Hi, thanks for this great article.

    can this example work with regualr website and not faceboot app?
    i want to DOM the og:image meta after the page loads with JS so i use:

    $(‘meta[property=og\\:image]’).attr(‘content’, newImageUrl);

    the problem is facebook ignors the DOM by reading only the original HTML
    how can i make him reload mata tags after page load?

    • Hi Daniel,
      Unfortunately you can’t. That’s why I wrote this article after lots of researching and experimentation. πŸ™‚ You can change the meta data on the server side based on some get parameters. Except that I can’t think of any other option.

  30. to resolve the image problem, you can set “og:image:width” and “og:image:height”

    • Hi Gustavo,
      Good advice, but it didn’t help. I already have meta tags with og:image:width and og:image:height. But the problem is when we want to share different data then in meta tags. I tried to put og:image:width and og:image:height in action_properties object, but it didn’t do any difference.
      (In the meanwhile I discovered that using action_type: ‘og.likes’ instead of action_type: ‘og.shares’ will display bigger image).

  31. Hi Great post, But I have an issue, when I sharing the post images it is small in preview and also after posting in facebook

    As per fb standards I’m using the image size morethan 600px ie: 800 x 398 my image resolution. But always it smaller for e.g https://imgur.com/o8qkzfY

  32. Wise, like Yoda, my man you are!! Thanks for this great article! Was having huge troubles with this. Much appreciated!

  33. Btw, I was also having issues with the image displaying small on the left. The way I resolved this was to actually swop the
    β€˜og:likes back to β€˜og:shares’. Not sure which is the correct one, I guess anyone can just try either or and see what works

    • I was tried with both og.likes and og.shares but in both cases, it is smaller in size. Please any one can give me a solution for this.

    • This works for me. i originally use og.likes, the result si small image. Then i change to og.shares. and it display full width image

    • It turns out that my solution only works for just some user. When i logged in with different account, it still display the small image even when i change to both og.likes and og.shares. Now i am confused.

      Can anyone solve this problem?

    • Updated info. When you check on the mobile apps, it turns out just fine. the image is full width. the small image only apply on website and mobile web. So it’s fine with me. thanks for this article

  34. i have used code but when i change contain title and share it show me error “Graph returned an error: This authorization code has been used.”

    How can i fixed it.

    please reply me on my email as soon as possible.

    Thanks,

  35. Hello drib,
    i have use this code but when i share it show me in feed share view how can i share with large size image. please reply me as soon as possible on my email.

    Thanks,

  36. Hello Drib,
    Thanks for the document. After doing all the changes you mentioned, If I open my link in a new tab, it is popping up nicely with the title and image and I am able to post my page in Facebook. But what I need is if my share my page link it show meta-information like the title and images. Looks like the og:url hasn’t take any effort, even the FB’s open graph dubugger shows there is no og:title or og:image in the page. The title and image should show when I am pasting the URL in WhatsApp or Facebook, how should I fix this, please advice

  37. Hello people πŸ™‚ For those who are wondering how to get rid of the message [Nils] likes an object on TestApp, the solution which I found above in the comments is to use action_type: β€˜og.shares’ instead of action_type: β€˜og.likes’. The layout is a little different though, but it’s ‘better’ than likes an object message…

    • My bad… it’s not displayed anymore in the popup, but on the feed it still shows like ‘Nils likes an object on TestApp’ πŸ™ if someone finds a solution for this, please share it πŸ˜€

  38. In response to Developer Kre about getting the post-id in the response. According to the FB docs:

    Only available if the user is logged into your app using Facebook and has granted publish_actions. If present, this is the ID of the published Open Graph story.

    And, FB have killed the publish_actions permission, so it will always be an empty list until they provide some other way to allow you access to this data.

  39. And, finally – if anyone is trying to do this using the react-facebook-sdk npm package. You’ll want the below:


    class App extends Component {
    render() {
    const action_properties = JSON.stringify({
    object: {
    'og:url': 'http://example.com',
    'og:title': 'Your Title',
    'og:description': 'Your description',
    'og:image': 'http://example.com/image.jpg',
    }
    })

    return (

    Share

    )
    }
    }

    • Hi PandaMaker,

      Thank you for reporting this. It did work before (TM). I am a little bit busy at this moment, but I will investigate as soon as possible.

  40. Delete previous comment for typo

    Using og.likes
    – Firefox: postage stamp image
    – Chrome: full width image
    Using og.shares
    – Firefox: full width image
    – Chrome: postage stamp image

  41. Hi. I am using php, and all I want to do is to dynamic change the og image.
    Do you suppose I could do that.
    I have tried several manipulations but I am not being able to override the og image
    Thanks

  42. Is it possible to add the meta tags on the fly? What I mean is for the meta tags to be not hard coded but added on the fly? I know it is possible to dynamically create meta tags and then add them to the Dom. But the question is will the meta tag work or take effect?

    • Hi, It will not work with Javascript on the client side (browser). It will work if you generate different meta tags on the server side. For example with php depending on the get params.

  43. Does the image size still work for you drip?, It does not for me, when I try your working example

  44. Hello there;
    great share mate thanks;
    I’m building idea where i want to share a random image in the OG for Facebook each time my link shared there; without the action it self ; meaning each time anyone type the URL a random picture from the site will appear, in the PHP side i did that with no problem, the link can be changer for the og:image, but still Facebook share the same image always.
    how could i apply your idea without the click button action ?!! is that possible .
    thanks

  45. og.shares vs og.likes, both display a small image. There is any other things that I can do to display a full image?

    • Hi,
      Unfortunately I am unable to reproduce the problem that you reported. So I can’t help you. Sorry.
      Damir

Submit a comment