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)}`;;

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 line.

Triff and Marv.

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, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)