onClick: share image on Facebook

2019-02-03 15:59发布

问题:

I would like to setup an onClick function to an image on my new website that launch Facebook sharer.

Here are some pieces of code that may help understand what I'm talking about

<div id="mImageBox">
<img id='my_image' src='' width="auto" height="auto"/>
</div>

The image src is blank because it's injected by another JavaScript function by using "my_image"

so, I tried to setup the onClick function with this method:

<script>function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script>

<div id="mImageBox">
<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank"><img id='my_image' src='' width="auto" height="auto"/></a>
</div>

The onClick function works well, however, it links to the page where the img is located and not the img itself!

Have you got any suggestion for me?

回答1:

try this:

<div id="mImageBox">
<img id='my_image' src='' alt='' width="auto" height="auto" onclick="fbs_click(this)"/>
</div>

<script>
     function fbs_click(TheImg) {
     u=TheImg.src;
     // t=document.title;
    t=TheImg.getAttribute('alt');
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;
}
</script>

You don't need to use <a> tag (surrounding the <img> tag) for case that JS disabled, because in that case the JS that should inject the src attribute will not work also.



回答2:

Just call below function and you can share Image with your Link and Text on Facebook.

function sharefbimage() {
    FB.init({ appId: `your appid`, status: true, cookie: true });
    FB.ui(
    {
        method: `share`,
        name: 'Facebook Dialogs',
        href: $(location).attr('href'),
        link: 'https://developers.facebook.com/docs/dialogs/',
        picture: 'your image url',
        caption: 'Ishelf Book',
        description: 'your description'
    },
    function (response) {
        if (response && response.post_id) {
            alert('success');
        } else {
            alert('error');
        }
    }
);


回答3:

Since Facebooks Javascript API 2.9 is dead since last week the solution above doesn't work any more ( I took me half a day to find this out!!! ). In v2.10 the picture-parameter of FB.ui doesn't exist any more. But I found a workaround generating an individual URL parameter for each image so Facebook has to scrape Open Graph data for each shared image individually. I've shared my code in this post for your reference.