If you are using Chrome or the new Edge browser, you might have noticed that opening a page from Google Search highlights and scrolls to the text that had your search query.
The magic ✨ here is in the URL.
#:~:text= part of the URL is the part of a new text fragment specification. It's currently supported in Chrome, Opera and Edge.
It's mostly useful for search engines to directly link to and highlight text (which might explain why the Chromium browsers have it) but it can also be used by anyone.
There is a lot to unravel from the spec, but let us look at the simplest URL fragment:
#:~: is the part that seperates the text fragment from rest of the URL.
text= would be the query parameter indicating that it is text that is to be scrolled to, it's value indicates the text.
// We use getSelection to get string version of text const text = window.getSelection().toString(); // We add the text to current URL and URL encode the text const newUrl = window.location.href + "#:~:text=" + c; console.log(newUrl);
This makes it very easy to implement it on your blog or website, but how do we create links to other people's pages?
Here is a bookmarklet to help:
You can copy the above text and add a bookmark in your browser with this as URL. Next time you click on the bookmark with text selected, you will have the URL with text ready.
Adding a bookmarklet to Chrome:
Using the Bookmarket:
There are lots of restrictions to this that you can find on the spec. But an important one being that you can only link to complete words (for some reason), so if you have a half of a word, won't work.
There more to the spec like adding context, and specifying start and end text, I suggest you read through if Mozilla implements it or if you are just bored.
Have fun 😁