简体   繁体   中英

Twitter & Facebook Custom Share Buttons With Dynamic URL & Title

I have the Twitter button working, but the Facebook button isn't. The Facebook popup loads, but then it disappears. There are no errors in the Chrome console.

HTML

<i onclick="fbs_click();" class="fa fa-facebook article-tab-sub"></i>
<i onclick="twr_click();" class="fa fa-twitter article-tab-sub"></i>

Javascript

function twr_click() {
    var twtTitle = document.title;
    var twtUrl = location.href;
    var maxLength = 140 - (twtUrl.length + 1);
    if (twtTitle.length > maxLength) {
        twtTitle = twtTitle.substr(0, (maxLength - 3)) + '...';
    }
    var twtLink = 'http://twitter.com/home?status=' + encodeURIComponent(twtTitle + ' ' + twtUrl);
    var x = screen.width/2 - 280/2; var y = screen.height/2 - 280/2; window.open(twtLink, '','height=280,width=280,left='+x+',top='+y);
}
function fbs_click() {
    var fbsTitle = document.title;
    var fbsUrl = location.href;
    var maxLength = 140 - (fbsUrl.length + 1);
    if (fbsTitle.length > maxLength) {
        fbsTitle = fbsTitle.substr(0, (maxLength - 3)) + '...';
    }
    var fbsLink = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(fbsTitle + ' ' + fbsUrl);
    var x = screen.width/2 - 280/2; var y = screen.height/2 - 280/2; window.open(fbsLink, '','height=280,width=280,left='+x+',top='+y);
}

You're not forming the fbsLink variable correctly. I looked here and found that the u attribute should only be the url and that the title should be separate. Here's a fixed line of code:

var fbsLink = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(fbsUrl) + '&title=' + encodeURIComponent(fbsTitle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM