javascript - Twitter 分享按钮显示空白页面。为什么?

标签 javascript html css

我想在博客文章上分享我的 Twitter 按钮。 20 个帖子中有 18 个运行良好。只有 2 个帖子有问题。单击按钮时会出现空白窗口,没有文本、URL 和via 等...

网址

  1. National Tour Announced For Disney’s The Little Mermaid
  2. 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 来代替。

顺便说一句

  1. tweet button documentation 中不支持 share 参数。 url 就足够了。
  2. document.title 与长版本 document.getElementsByTagName('title')[0].innerHTML 一样完美。
  3. 如果未使用,请勿创建额外的全局变量 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/

相关文章:

javascript - 编码字符串javascript,以便它可以传输到服务器

javascript - 滚动事件监听器在 iFrame 中的 iOS 上不起作用

javascript - key 代码 13 不起作用

javascript - 通过 PeerConnection 发送带有 Web 音频效果的 MediaStream 对象

jQuery-Mobile 禁用页面拖动并防止滚动页眉/页脚

html - 带有 "window"的 PNG 图像覆盖在另一幅图像上

javascript - Javascript 如何区分 Json 对象和字符串?

javascript - 在 chrome 中使用 css 分页符属性进行打印的解决方法?

php - 将 JSON 从 php 传递到 javascript

html - 如何修复意外的背景溢出