Osmani
Osmani

Reputation: 300

Twitter share button shows blank page. Why?

I want to share my twitter button on the blog posts. It is working fine in 18 posts out of 20. Only 2 posts have problems. The blank window appears on clicking the button with no text, url and via etc...

The URLS

  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

Is my code good or what happened here ? Please assist me.

.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>

Upvotes: 2

Views: 1099

Answers (1)

charlee
charlee

Reputation: 1369

Looking at Chrome Developer console you will find out twitter server returned a 400 error. That was because you didn't encode the url (especially, the title parameter) correctly.

Note the %u2019 character after the Disney. Its an encoded unicode character. Actually twitter expects you encode it as UTF-8.

text=National%20Tour%20Announced%20for%20Disney%u2019s%20The%20Little%20Mermaid

The solution is to use encodeURIComponent() instead of escape(). This code should work fine:

<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>

Anyway escape() is deprecated so please try encodeURIComponent instead.

BTW

  1. There's no share parameter supported in tweet button documentation. url is enough.
  2. document.title works as perfect as the long version document.getElementsByTagName('title')[0].innerHTML.
  3. Don't create an extra global variable tweetShare, if not used.

So this may be simplified as:

<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>

Upvotes: 3

Related Questions