简体   繁体   中英

Twitter Share button dynamic URL share

I'm trying to make a custom Twitter button that will grab the page URL of the current page when clicked, which would obviously change dependent on which page it appears on, not unlike the default share button. However, I am unsure how to pass the page URL into the button.

This is what I have thus far jsfiddle

<style type="text/css" media="screen">

</style>
<div id="social-share-container">
<div id="custom-tweet-button">
 <a id="tweetShare" href="https://twitter.com/share?url="+encodeURIComponent(document.URL); target="_blank">Tweet
    </a>
</div>
</div>

It's a bit hacked together as I'm pretty unfamiliar with JS.

This passes the url and title to a simple pop-up box with the twitter share page:

<script language="javascript">
    function tweetCurrentPage()
    { window.open("https://twitter.com/share?url="+ encodeURIComponent(window.location.href)+"&text="+document.title, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false; }
</script>

<a class="tweet" href="javascript:tweetCurrentPage()" target="_blank" alt="Tweet this page">Tweet this page</a>

If you don't want it to open in a popup box, you can use this instead of window.open :

window.location.href="https://twitter.com/share?url="+ encodeURIComponent(window.location.href)+"&text="+document.title;

Update: escape() function is deprecated, Replaced with encodeURIComponent()

I would suggest window.location - That will give you the current page url.

Problem is you're using JS inline in HTML - you can't do that like you're wanting to.

I updated your fiddle with some vanilla js to show you a better way to do this.

http://jsfiddle.net/4jF5N/1/

var link = document.getElementById('tweetShare');
var url = window.location;

link.addEventListener('click',function(event){
    event.preventDefault();

    window.open("https://twitter.com/share?url="+encodeURIComponent(url));
    alert(url)
},false);

Take a look on document.location:
location.hostname
location.pathname
http://www.w3schools.com/jsref/obj_location.asp

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