user2472523
user2472523

Reputation: 113

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.

Upvotes: 7

Views: 14737

Answers (2)

Graham Corlet
Graham Corlet

Reputation: 1

$Url = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
$Url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];

<div class="fb-share-button" data-href="<?php echo $Url; ?>" data-layout="button_count" data-size="small">

<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $Url; ?>&amp;src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a></div>

Upvotes: 0

tomasantunes
tomasantunes

Reputation: 945

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>

Upvotes: 6

Related Questions