Get current page URL and append it to Facebook Share link (with javascript)
12,667
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>
Author by
user2472523
Updated on June 18, 2022Comments
-
user2472523 almost 2 years
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.
-
Muaaz over 4 yearsYou just need to add var fbShareLink = document.getElementById('fb-share-link');
-
Admin almost 4 yearsOh, with java, my bad. Oh well, this might help some other person. ;)
-
Alpi Murányi almost 4 yearsHi Graham and thanks for the contribution! Can you please add some explanation to your answer? Indeed, also the clarification of the coding language used would be useful for some future readers. Thank you and keep on stackoverflowing!
-
wynx almost 3 yearsit helped me! thanks haha. using php here