Christian Heilmann

“Tweet this page” bookmarklet

Friday, August 23rd, 2019 at 9:42 pm

Update: Moved the code to GitHub, make sure to drag it from there to your toolbars
Update: Fixed now for Chrome – there were some issues with whitespace :(

I like tweeting about pages I read in the following format:

"Headline"
https://example.com

Most “share this” buttons add a lot of cruft and if there is none, it is annoying having to copy the text first and then the URL into Twitter.

With this bookmarklet, you can highlight some text, click the bookmarklet and get a tweet window in a new tab. This is the source in a more readable manner – this will not work as a bookmarklet, see the link below instead!

(function(){
    n=getSelection().anchorNode;
    if(!n) {
        t = document.title;
    } else {
        t = n.nodeType === 3 ? n.data : n.innerText;
    }
    t = '“' + t.trim() + '”\n\n';
    window.open(
        `https://twitter.com/intent/tweet?text=
        ${encodeURIComponent(t)}
        ${document.location.href}`
    )
})();

Explanation:

  • We wrap the whole thing in an IIFE to avoid the browser redirecting to “javascript://”
  • We get the anchorNode of the current Selection object
  • If there is no highlighted text, we grab the document title
  • We check the type. If it’s a text node, we read the data, if it is HTML, we get the innerText
  • We remove any whitespace, add the quotes and some line breaks
  • We open a window (which these days results in a new tab) and call the Twitter intend with the text followed by two line breaks and the URL of the document.

That’s it. Drag the bookmarklet to the toolbar from the GitHub Demo page or check the code.

Voilà, happy tweeting.

Share on Mastodon (needs instance)

Share on Twitter

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

Dev Digest 146: 🥱 React fatigue 📊 Query anything with SQL 🧠 AI News

Why it may not be needed to learn React, why Deepfake masks will be a big problem and your spirit animal in body fat! 

Dev Digest 147: Free Copilot! Panel: AI and devs! RTO is bad! Pi plays!

Free Copilot! Experts discuss what AI means for devs. Don't trust containers. Mandated RTO means brain drain. And Pi plays Pokemon!

Dev Digest 148: Behind the scenes of Dev Digest & end of the year reports.

In 50 editions of Dev Digest we gave you 2081 resources. Join us in looking back and learn about all the trends this year.

Dev Digest 149: Wordpress break, VW tracking leak, ChatGPT vs Google.

Slowly starting 2025 we look at ChatGPT vs Google, Copilot vs. Cursor and the state of AI crawlers to replace web search…

Dev Digest 150: Shifting manually to AI.

Manual coding is becoming less of a skill. How can we ensure the quality of generated code? Also, unpacking an APK can get you an AI model.

My other work: