Linking to Text Fragments with a Bookmarklet

2 hours ago 2

One of my favourite features added to web browsers in the last few years is text fragments.

Text fragments allow you to link directly to specific text on a web page, and some browsers will highlight the linked text – for example, by scrolling to it, or adding a coloured highlight. This is useful if I’m linking to a long page that doesn’t have linkable headings – I want it to be easy for readers to find the part of the page I was looking for.

Here’s an example of a URL with a text fragment:

https://example.com/#:~:text=illustrative%20examples

But I don’t find the syntax especially intuitive – I can never remember exactly what mix of colons and tildes to add to a URL.

To help me out, I’ve written a small bookmarklet to generate these URLs:

Create link to selected text

To install the bookmarklet, drag it to my bookmarks bar.

When I’m looking at a page and want to create a text fragment link, I select the text and click the bookmarklet. It works out the correct URL and shows it in a popup, ready to copy and paste. You can try it now – select some text on this page, then click the button to see the text fragment URL.

It’s a small tool, but it’s made my link sharing much easier.

Bookmarklet source code

This is the JavaScript that gets triggered when you run the bookmarklet:

const selectedText = window.getSelection().toString().trim(); if (!selectedText) { alert("You need to select some text!"); return; } const url = new URL(window.location); url.hash = `:~:text=${encodeURIComponent(selectedText)}`; alert(url.toString());
Read Entire Article