Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current page URL and append it to Facebook Share link (with javascript)

I've been trying really hard to make the Facebook share button work, but no luck. I'd like to have the same code on ALL my pages, so I need to be able to dynamically get the current page url and append it to the Facebook share URL.

The best I could come up with is the following:

<a href="" onclick="window.open('http://www.facebook.com/share.php?u=' + 
encodeURIComponent(location.href))">Share this page</a>

https://jsfiddle.net/08x2sufs/2/

However, as you can see from the jsFiddle demo, the link does take us to a Facebook share page, but there is no page to share.

Thank you for your help.

like image 328
user2472523 Avatar asked Mar 29 '16 20:03

user2472523


1 Answers

I would use the following approach:

<a href="" id="fb_share">Share this page</a>

<script>
    window.onload = function() {
        fb_share.href ='http://www.facebook.com/share.php?u=' + encodeURIComponent(location.href); 
    }  
</script>
like image 112
tomasantunes Avatar answered Sep 28 '22 09:09

tomasantunes