Scroll to text bookmarklet

I forgot that Scroll to Text fragment was a thing that is launching soon in Chrome (81 and not 80 as mentioned in Chrome Status), until I saw this Tweet.

I love this feature, it let’s you link to more than just named elements. Domenic Denicola asked if there was an extension that did this. I don’t think you need one, because bookmarklets are awesome and underused. I decieded that it should be pretty quick to write up a simple bookmarklet that creates a link with a scroll to text anchor that you can share with people.

Here it is. It get’s the selected text, and creates a new URL and opens a window. I’ve noticted that ‘scroll to text’ can only scroll to whole words so I might need to add some logic that extends the selection so that it picks up partial words correctly.

const selectedText = getSelection().toString();
const newUrl = new URL(location);
newUrl.hash = `:~:text=${encodeURIComponent(selectedText)}`;
window.open(newUrl);

If you have Chrome 81 then you can drag this Find in page bookmarklet to your address bar and easily create links that link to content.

It’s not too hard to extend this, for example if you wanted to just paste on to the clipboard you could do that by replacing the window.open line.

Triff and Marv.

Picture of me smiling.

Paul Kinlan

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

RSS Github Medium