Some Bits: Nelson's log

Link to text fragment

I’ve noticed something since switching to Chrome: sometimes when I click on a search result some text is highlighted on the page. Turns out this is called text fragments. More docs here and a general interest article here or here. Th ey date to 2020 and work in all major browsers but Firefox.

For example searching Google for [coconut milk chicken marinade] leads an in-line “People also ask” result. Clicking that result leads to a special anchored URL that causes Chrome to navigate to and highlight the relevant result. It’s a way to make a deep link into a particular piece of a page, based on its text content, without the page having an explicit anchor to link to.

The text fragment link syntax is

https://example.com#:~:text=[prefix-,]textStart[,textEnd][,-suffix]

There’s a standards proposal here (and a W3C document) that talks about some subtleties. There’s escaping, of course. There’s an HTTP directive for a page to opt out of the behavior. The browser applies a :target CSS pseudo-class to let the site customize the highlight style. Also a little bit of Javascript API for the feature.

The syntax :~:text= made me wonder what other possibilities there were. MDN calls the :~: a “fragment directive” but so far text seems to be the only option. :~: was chosen because it wasn’t seen anywhere on the Web at the time the proposal was written.

Google released a browser extension to easily create text fragment links.

Update: see also fragmentations, an alternate proposal which just normalizes putting plaintext phrases in an anchor. The Mozilla folks seem to prefer that. I’m not sure any browsers really do anything for them; the implementations I’ve seen involve Javascript or an extension.