我想在博客文章上分享我的 Twitter 按钮。 20 个帖子中有 18 个运行良好。只有 2 个帖子有问题。单击按钮时会出现空白窗口,没有文本、URL 和via 等...
网址
- National Tour Announced For Disney’s The Little Mermaid
- MLB Venues – How A Team’s Form Is Effecting Ticket Prices At Their Homes
我的代码好还是这里发生了什么?请帮助我。
.tweet{ margin:0px auto; width:200px; text-align:center;}
.tweet a{ display:inline-block; line-height:50px; color:#f00; text-decoration:none; background:#ccc; border-radius:5px; padding:0px 20px;}
<div class="tweet">
<a title="Twitter" href="//twitter.com/intent/tweet?share=" onclick="tweetShare=window.open(this.href+escape(window.location)+'&text='+escape(document.getElementsByTagName('title')[0].innerHTML)+'&url='+location.href+'&via=ExciteEventstix','tweetShare','toolbar=no,status=no,width=640,height=400,scrollbars=no'); return false;"
target="_blank">Twitter</a></div>
最佳答案
查看 Chrome 开发者控制台,您会发现 Twitter 服务器返回了 400 错误。这是因为您没有正确编码 url(尤其是 title
参数)。
请注意 Disney
后面的 %u2019
字符。它是一个编码的 unicode 字符。实际上 Twitter 希望您将其编码为 UTF-8。
text=National%20Tour%20Announced%20for%20Disney%u2019s%20The%20Little%20Mermaid
解决方案是使用encodeURIComponent()
而不是escape()
。这段代码应该可以正常工作:
<div class="tweet">
<a title="Twitter" href="//twitter.com/intent/tweet?share=" onclick="tweetShare=window.open(this.href+encodeURIComponent(window.location)+'&text='+encodeURIComponent(document.getElementsByTagName('title')[0].innerHTML)+'&url='+location.href+'&via=ExciteEventstix','tweetShare','toolbar=no,status=no,width=640,height=400,scrollbars=no'); return false;"
target="_blank">Twitter</a></div>
无论如何escape()
是deprecated所以请尝试使用 encodeURIComponent
来代替。
顺便说一句
- tweet button documentation 中不支持
share
参数。url
就足够了。 document.title
与长版本document.getElementsByTagName('title')[0].innerHTML
一样完美。- 如果未使用,请勿创建额外的全局变量
tweetShare
。
所以这可以简化为:
<div class="tweet">
<a title="Twitter" href="javascript:window.open('https://twitter.com/intent/tweet?url='+encodeURIComponent(location.href)+'&text='+encodeURIComponent(document.title)+'&via=ExciteEventstix','tweetShare','toolbar=no,status=no,width=640,height=400,scrollbars=no')">Twitter</a></div>
关于javascript - Twitter 分享按钮显示空白页面。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31933089/