Detect browser support of the Scroll-To-Text Fragment (:~:text=) feature?

Viewed 234

Google recently started to roll out the Scroll-To-Text Frament feature in their highlighted snippets. Doing so it appends #:~:text=... parameter to linked url which is used by the browser to highlight the snippets text on the targets website.

As for now (July 2020), Scroll-To-Text Fragment is a W3C Community Group Draft Report and the browser support is very limited (basically Chromium based browsers as of today).

My question is: is there any way to detect whether a browser supports this feature? I.e. using javascript?

1 Answers

From the spec:

3.7. Feature Detectability

For feature detectability, we propose adding a new FragmentDirective interface that is exposed via document.fragmentDirective if the UA supports the feature.

[Exposed=Window]
interface FragmentDirective {};

We amend the Document interface to include a fragmentDirective property:

partial interface Document {
    [SameObject] readonly attribute FragmentDirective fragmentDirective;
};

So you can test this using

const isAvailable = "fragmentDirective" in window.document;

or

const isAvailable = !!window.FragmentDirective;
Related