DEV Community

Christian Heilmann
Christian Heilmann

Posted on • Updated on

A simple bookmarklet to tweet the current page

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:

javascript:(function(){
  n=getSelection().anchorNode;
  t=n.nodeType===3?n.data:n.innerText;t=''+t+'\\n\\n';
  window.open(`https://twitter.com/intent/tweet?
  text=${encodeURIComponent(t)}${document.location.href}`)
})()
Enter fullscreen mode Exit fullscreen mode

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
  • We check the type. If it's a text node, we read the data, if it is HTML, we get the innerText
  • We open a window (which these days results in a new tab) and call the Twitter intend with the text followed by two linebreaks and the URL of the document.

That's it.

Here's the minified version to add to your bookmarks:

javascript:(function(){n=getSelection().anchorNode;t=n.nodeType===3?n.data:n.innerText;t='“'+t+'”\\n\\n';window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(t)}${document.location.href}`)})()
Enter fullscreen mode Exit fullscreen mode

Copy this, go to your bookmarks toolbar (change in view if it isn't visible), and set the location as the code above:

Bookmark settings

Alternatively, go to the post on my blog (as dev.to disallows javascript: links) and drag the "tweet this" link to your toolbar.

Voilà, happy tweeting.

Top comments (6)

Collapse
 
dazzknowles profile image
Dazz Knowles

Anyone got this working on Chrome (76.0.3809.100, Windows)? It does nothing when I then click on the bookmark.

Collapse
 
codepo8 profile image
Christian Heilmann

Oops, there was a bug, I am editing this now. You can also drag the bookmarklet link on my blog into the chrome bar:

christianheilmann.com/2019/08/23/t...

Collapse
 
dazzknowles profile image
Dazz Knowles

All working now, thanks and good work :)

Collapse
 
cescquintero profile image
Francisco Quintero 🇨🇴

I suffer the want thing when I want to share stuff.

Giving this a shot

Collapse
 
jankoweb profile image
Janko

Text is not inserted in Chrome. I think that the url changed to twitter.com/compose/tweet .

Collapse
 
jankoweb profile image
Janko

this work for me:

javascript:void%20function(){url=window.location,window.getSelection%3Fselection=window.getSelection():document.getSelection%3Fselection=document.getSelection():document.selection%26%26(selection=document.selection.createRange().text),selection+=%22%22,str=selection,url2open=%22twitter.com/compose/tweet%3Ftext=%...;