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:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: πŸ•ΉοΈ Super Mario AI πŸ”‘ API keys in LLMs πŸ€™πŸΎ Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: