1. Infrastructure
This specification depends on the Infra Standard. [INFRA]
2. Introduction
2.1. Use cases
2.1.1. Web text references
The core use case for text fragments is to allow URLs to serve as an exact text reference across the web. For example, Wikipedia references could link to the exact text they are quoting from a page. Similarly, search engines can serve URLs that direct the user to the answer they are looking for in the page rather than linking to the top of the page.2.1.2. User sharing
With text fragments, browsers may implement an option to 'Copy URL to here' when the user opens the context menu on a text selection. The browser can then generate a URL with the text selection appropriately specified, and the recipient of the URL will have the specified text conveniently indicated. Without text fragments, if a user wants to share a passage of text from a page, they would likely just copy and paste the passage, in which case the receiver loses the context of the page.3. Description
3.1. Indication
This specification intentionally doesn’t define what actions a user agent should or could take to "indicate" a text match. There are different experiences and trade-offs a user agent could make. Some examples of possible actions:
-
Providing visual emphasis or highlight of the text passage
-
Automatically scrolling the passage into view when the page is navigated
-
Activating a UA’s find-in-page feature on the text passage
-
Providing a "Click to scroll to text passage" notification
-
Providing a notification when the text passage isn’t found in the page
3.2. Syntax
A text fragment directive is specified in the fragment directive (see § 3.3 The Fragment Directive) with the following format:
#:~:text=[prefix-,]textStart[,textEnd][,-suffix] context |-------match-----| context
(Square brackets indicate an optional parameter)
The text parameters are percent-decoded before matching. Dash (-), ampersand (&), and comma (,) characters in text parameters must be percent-encoded to avoid being interpreted as part of the text directive syntax.
The only required parameter is textStart. If only textStart is specified, the first instance of this exact text string is the target text.
#:~:text=an%20example%20text%20fragment
indicates that the
exact text "an example text fragment" is the target text. If the textEnd parameter is also specified, then the text directive refers to a range of text in the page. The target text range is the text range starting at the first instance of startText, until the first instance of endText that appears after startText. This is equivalent to specifying the entire text range in the startText parameter, but allows the URL to avoid being bloated with a long text directive.
#:~:text=an%20example,text%20fragment
indicates that the first
instance of "an example" until the following first instance of "text fragment"
is the target text. 3.2.1. Context Terms
The other two optional parameters are context terms. They are specified by the dash (-) character succeeding the prefix and preceding the suffix, to differentiate them from the textStart and textEnd parameters, as any combination of optional parameters may be specified.
Context terms are used to disambiguate the target text fragment. The context terms can specify the text immediately before (prefix) and immediately after (suffix) the text fragment, allowing for whitespace.
The context terms are not part of the targeted text fragment and must not be visually indicated.
#:~:text=this%20is-,an%20example,-text%20fragment
would match
to "an example" in "this is an example text fragment", but not match to "an
example" in "here is an example text". 3.3. The Fragment Directive
To avoid compatibility issues with usage of existing URL fragments, this spec introduces the fragment directive. The fragment directive is a portion of the URL fragment delimited by the code sequence:~:
. It is
reserved for UA instructions, such as text=, and is stripped from the URL
during loading so that author scripts can’t directly interact with it.
The fragment directive is a mechanism for URLs to specify instructions meant for the UA rather than the document. It’s meant to avoid direct interaction with author script so that future UA instructions can be added without fear of introducing breaking changes to existing content. Potential examples could be: translation-hints or enabling accessibility features.
3.3.1. Parsing the fragment directive
To the definition of Document, add:
Each document has an associated fragment directive which is either null or an ASCII string holding data used by the UA to process the resource. It is initially null.
The fragment directive delimiter is the string ":~:", that is the three consecutive code points U+003A (:), U+007E (~), U+003A (:).
Amend the create and initialize a Document object steps to parse and remove the fragment directive from the Document’s URL.
Replace steps 7 and 8 of this algorithm with:
-
Let url be null
-
If request is non-null, then set document’s URL to request’s current URL.
-
Otherwise, set url to response’s URL.
-
Let raw fragment be equal to url’s fragment.
-
Let fragmentDirectivePosition be an integer initialized to 0.
-
While the substring of raw fragment starting at position fragmentDirectivePosition does not begin with the fragment directive delimiter and fragmentDirectivePosition does not point past the end of raw fragment:
-
Increment fragmentDirectivePosition by 1.
-
-
If fragmentDirectivePosition does not point past the end of raw fragment:
-
Let fragment be the substring of raw fragment starting at 0 of count fragmentDirectivePosition.
-
Advance fragmentDirectivePosition by the length of fragment directive delimiter.
-
Let fragment directive be the substring of raw fragment starting at fragmentDirectivePosition.
-
Set url’s fragment to fragment.
-
Set document’s fragment directive to fragment directive. (Note: this is stored on the document but not web-exposed)
-
-
Set document’s URL to be url.
https://example.org/#test:~:text=foo
will be parsed such that
the fragment is the string "test" and the fragment directive is the string
"text=foo". To parse a text directive, on a string string, run these steps:
This algorithm takes a single text directive string as input (e.g. "text=prefix-,foo,bar") and attempts to parse the string into the components of the directive (e.g. ("prefix", "foo", "bar", null)). See § 3.2 Syntax for the what each of these components means and how they’re used.
Returns null if the input is invalid or fails to parse in any way. Otherwise, returns a ParsedTextDirective.
-
Assert: raw target text matches the production TextDirective.
-
Let raw target text be the substring of text directive input starting at index 5.
This is the remainder of the text directive input following, but not including, the "text=" prefix. -
Let tokens be a list of strings that is the result of splitting raw target text on commas.
-
If tokens has size less than 1 or greater than 4, return null.
-
If any of tokens’s items are the empty string, return null.
-
Let retVal be a ParsedTextDirective with each of its items initialized to null.
-
Let potential prefix be the first item of tokens.
-
If the last character of potential prefix is U+002D (-), then:
-
Let potential suffix be the last item of tokens, if one exists, null otherwise.
-
If potential suffix is non-null and its first character is U+002D (-), then:
-
If tokens has size not equal to 1 nor 2 then return null.
-
Set retVal’s textStart be the first item of tokens.
-
If tokens has size 2, then set retVal’s textEnd be the last item of tokens.
-
Return retVal.
A ParsedTextDirective is a struct that consists of four strings: textStart, textEnd, prefix, and suffix. textStart is required to be non-null. The other three items may be set to null, indicating they weren’t provided. The empty string is not a valid value for any of these items.
See § 3.2 Syntax for the what each of these components means and how they’re used.
3.3.2. Fragment directive grammar
A valid fragment directive is a sequence of characters that appears in the fragment directive that matches the production:- FragmentDirective ::=
- (TextDirective | UnknownDirective) ("&" FragmentDirective)?
- UnknownDirective ::=
- CharacterString
The text fragment directive is one such fragment directive that enables specifying a piece of text on the page, that matches the production:
- TextDirective ::=
- "text=" TextDirectiveParameters
TextDirectiveParameters ::=
(TextDirectivePrefix ",")? CharacterString ("," CharacterString)? ("," TextDirectiveSuffix)?
TextDirectivePrefix ::=
CharacterString "-"
TextDirectiveSuffix ::=
"-" CharacterString
CharacterString ::=
(ExplicitChar | PercentEncodedChar)+
ExplicitChar ::=
[a-zA-Z0-9] | "!" | "$" | "'" | "(" | ")" | "*" | "+" | "." | "/" | ":" | ";" | "=" | "?" | "@" | "_" | "~"
A ExplicitChar may be any URL code point that is not explicitly used in the TextDirective syntax, that is "&", "-", and ",", which must be percent-encoded.- PercentEncodedChar ::=
- "%" [a-zA-Z0-9]+
3.4. Security and Privacy
3.4.1. Motivation
Care must be taken when implementing text fragment directive so that it cannot be used to exfiltrate information across origins. Scripts can navigate a page to a cross-origin URL with a text fragment directive. If a malicious actor can determine that the text fragment was successfully found in victim page as a result of such a navigation, they can infer the existence of any text on the page.
In addition, the user’s privacy should be ensured even from the destination origin. Although scripts on that page can already learn a lot about a user’s actions, a text fragment directive can still contain sensitive information. For this reason, this specification provides no way for a page to extract the content of the text fragment anchor. User agents must not expose this information to the page.
The following subsections restrict the feature to mitigate the expected attack vectors. In summary, the text fragment directives are invoked only on full (non-same-page) navigations that are the result of a user activation. Additionally, navigations originating from a different origin than the destination will require the navigation to take place in a "noopener" context, such that the destination page is known to be sufficiently isolated.
3.4.2. Scroll On Navigation
A UA may choose to automatically scroll a matched text passage into view. This can be a convenient experience for the user but does present some risks that implementing UAs should be aware of.
There are known (and potentially unknown) ways a scroll on navigation might be detectable and distinguished from natural user scrolls.
All known cases like this rely on specific circumstances about the target page so don’t apply generally. With additional restrictions about when the text fragment can invoke an attacker is further restricted. Nonetheless, different UAs can come to different conclusions about whether these risks are acceptable. UAs should consider these factors when determining whether to scroll as part of navigating to a text fragment.
Conforming UAs may choose not to scroll automatically on navigation. Such UAs may, instead, provide UI to initiate the scroll ("click to scroll") or none at all. In these cases UA should provide some indication to the user that an indicated passage exists further down on the page.
The examples above illustrate that in specific circumstances, it may be possible for an attacker to extract 1 bit of information about content on the page. However, care must be taken so that such opportunities cannot be exploited to extract arbitrary content from the page by repeating the attack. For this reason, restrictions based on user activation and browsing context isolation are very important and must be implemented.
However, it also ensures any malicious use is difficult to hide. A browsing context that’s the only one in a group must be a top level browsing context (i.e. a full tab/window).
If a UA does choose to scroll automatically, it must ensure no scrolling is performed while the document is in the background (for example, in an inactive tab). This ensures any malicious usage is visible to the user and prevents attackers from trying to secretly automate a search in background documents.
3.4.3. Search Timing
A naive implementation of the text search algorithm could allow information exfiltration based on runtime duration differences between a matching and non- matching query. If an attacker could find a way to synchronously navigate to a text fragment directive-invoking URL, they would be able to determine the existence of a text snippet by measuring how long the navigation call takes.
For this reason, the implementation must ensure the runtime of § 3.5 Navigating to a Text Fragment steps does not differ based on whether a match has been successfully found.
This specification does not specify exactly how a UA achieves this as there are multiple solutions with differing tradeoffs. For example, a UA may continue to walk the tree even after a match is found in . Alternatively, it may schedule an asynchronous task to find and set the indicated part of the document.
3.4.4. Restricting the Text Fragment
To determine whether a navigation should allow a text fragment, given as input a boolean is user triggered, an origin incumbentNavigationOrigin, and Document document; follow these steps:
-
If is user triggered is false, return false.
-
If the document of the latest entry in document’s browsing context's session history is equal to document, return false.
i.e. Forbidden on a same-document navigation. -
If incumbentNavigationOrigin is equal to the origin of document return true.
-
If document’s browsing context is a top-level browsing context and its group’s browsing context set has length 1 return true.
i.e. Only allow navigation from a cross-process element/script if the document is loaded in a noopener context. That is, a new top level browsing context group to which the navigator does not have script access and which may be placed into a separate process. -
Otherwise, return false.
To set the allowTextFragmentDirective flag, follow these steps:
Amend the page load processing model for HTML files to insert these steps after step 1:
-
Let is user activated be true if the current navigation was triggered by user activation
-
Set document’s allowTextFragmentDirective flag to the result of running should allow a text fragment with is user activated, incumbentNavigationOrigin, and the document.
Amend the try to scroll to the fragment steps by replacing the steps of the task queued in step 2:
-
If document has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment, then clear document’s allowTextFragmentDirective flag and abort these steps.
-
Scroll to the fragment given in document’s URL. If this does not find an indicated part of the document, then try to scroll to the fragment for document.
-
Clear document’s allowTextFragmentDirective flag
3.5. Navigating to a Text Fragment
Replace step 3.1 of the scroll to the fragment algorithm with the following:
-
Otherwise:
-
Let target, range be the element and range that is the indicated part of the document.
-
Replace step 3.3 of the scroll to the fragment algorithm with the following:
-
Otherwise:
-
If range is non-null:
-
If the UA supports scrolling of text fragments on navigation, invoke Scroll range into view, with containingElement target, behavior set to "auto", block set to "center", and inline set to "nearest".
-
-
Otherwise:
-
Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest".
This otherwise case is the same as the current step 3.3.
-
-
Add the following steps to the beginning of the processing model for the indicated part of the document:
-
Let fragment directive string be the document’s fragment directive.
-
If the document’s allowTextFragmentDirective flag is true then:
-
Let ranges be a list that is the result of running the process a fragment directive steps with fragment directive string and the document.
-
If ranges is non-empty, then:
-
Let range be the first item of ranges.
-
Let node be the first common ancestor of range’s start node and start node.
-
The indicated part of the document is node and range; return.
-
-
To find the first common ancestor of two nodes nodeA and nodeB, follow these steps:
-
Let commonAncestor be nodeA.
-
While commonAncestor is not a shadow-including inclusive ancestor of nodeB, let commonAncestor be commonAncestor’s shadow-including parent.
-
Return commonAncestor.
To find the shadow-including parent of node follow these steps:
-
If node is a shadow root, return node’s host.
-
Otherwise, return node’s parent.
3.5.1. Scroll a DOMRect into view
Move the scroll an element into view algorithm’s steps
3-14 into a new algorithm scroll a DOMRect into view, with input DOMRect
bounding box, ScrollIntoViewOptions
dictionary options, and element startingElement. Also move the
recursive behavior described at the top of the scroll an
element into view algorithm to the scroll a DOMRect into view algorithm: "run these steps for each ancestor element or viewport of startingElement that establishes a scrolling box scrolling
box, in order of innermost to outermost scrolling box".
Replace steps 3-14 of the scroll an element into view algorithm with a call to scroll a DOMRect into view:
-
Perform scroll a DOMRect into view on element bounding border box with options options and startingElement element.
Define a new algorithm scroll a Range into view, with input range range, element containingElement, and a ScrollIntoViewOptions
dictionary options:
-
Let bounding rect be the
DOMRect
that is the return value of invokinggetBoundingClientRect()
on range. -
Perform scroll a DOMRect into view on bounding rect with options and startingElement containingElement.
3.5.2. Finding Ranges in a Document
At a high level, we take a fragment directive string that looks like this:
text=prefix-,foo&unknown&text=bar,baz
We break this up into the individual text directives:
text=prefix-,foo text=bar,baz
For each text directive, we perform a search in the document for the first instance of rendered text that matches the restrictions in the directive. Each search is independent of any others; that is, the result is the same regardless of how many other directives are provided or their match result.
If a directive successfully matches to text in the document, it returns a range indicating that match in the document. The process a fragment directive steps are the high level API provided by this section. These return a list of ranges that were matched by the individual directive matching steps, in the order the directives were specified in the fragment directive string.
If a directive was not matched, it does not add an item to the returned list.
To process a fragment directive, given as input a string fragment directive input and a Document document, run these steps:
-
If fragment directive input does not match the FragmentDirective production, then return an empty list.
-
Let directives be a list of strings that is the result of strictly splitting the string fragment directive input on "&".
-
For each string directive of directives:
-
If directive does not match the production TextDirective, then continue.
-
Let parsedValues be the result of running the parse a text directive steps on directive.
-
If parsedValues is null then continue.
-
If the result of running find a range from a text directive given parsedValues and document is non-null, then append it to ranges.
-
-
Return ranges.
To find a range from a text directive, given a ParsedTextDirective parsedValues and Document document, run the following steps:
textEnd may be null. If omitted, this is an "exact" search and the returned range must contain a string exactly matching textStart. If textEnd is provided, this is a "range" search; the returned range must start with textStart and end with textEnd. In the normative text below, we’ll call a text passage that matches the provided textStart and textEnd, regardless of which mode we’re in, the "matching text".
Either or both of prefix and suffix may be null, in which case context on that side of a match is not checked. E.g. If prefix is null, text is matched without any requirement on what text precedes it.
:~:text=The quick,lazy dogwill fail to match in
<div>The<div> </div>quick brown fox</div> <div>jumped over the lazy dog</div>
because the starting string "The quick" does not appear within a single, uninterrupted block. The instance of "The quick" in the document has a block element between "The" and "quick".
It does, however, match in this example:
<div>The quick brown fox</div> <div>jumped over the lazy dog</div>
-
Let searchRange be a range with start (document, 0) and end (document, document’s length)
-
While searchRange is not collapsed:
-
Let potentialMatch be null.
-
If parsedValues’s prefix is not null:
-
Let prefixMatch be the the result of running the find a string in range steps given parsedValues’s prefix and searchRange.
-
If prefixMatch is null, return null.
-
Set searchRange’s start to the first boundary point after prefixMatch’s start
-
Let matchRange be a range whose start is prefixMatch’s end and end is searchRange’s end.
-
Advance matchRange’s start to the next non-whitespace position.
-
If matchRange is collapsed return null.
This can happen if prefixMatch’s end or its subsequent non-whitespace position is at the end of the document. -
Assert: matchRange’s start node is a
Text
node.matchRange’s start now points to the next non-whitespace text data following a matched prefix. -
Set potentialMatch to the result of running the find a string in range steps given parsedValues’s textStart and matchRange.
-
If potentialMatch is null, return null.
-
If potentialMatch’s start is not matchRange’s start, then and continue.
In this case, we found a prefix but it was followed by something other than a matching text so we’ll continue searching for the next instance of prefix. -
If parsedValues’s textEnd item is non-null, then:
-
-
Otherwise:
-
Set potentialMatch to the result of running the find a string in range steps given parsedValues’s textStart and searchRange.
-
If potentialMatch is null, return null.
-
Set searchRange’s start to the first boundary point after potentialMatch’s start
-
If parsedValues’s textEnd item is non-null, then:
-
-
Assert: potentialMatch is non-null, not collapsed and represents a range exactly containing an instance of matching text.
-
If parsedValues’s suffix is null, return potentialMatch.
-
Let suffixRange be a range with start equal to potentialMatch’s end and end equal to search range’s end.
-
Advance suffixRange’s start to the next non-whitespace position.
-
Let suffixMatch be result of running the find a string in range steps given parsedValues’s suffix and suffixRange.
-
If suffixMatch is null then return null.
If the suffix doesn’t appear in the remaining text of the document, there’s no possible way to make a match. -
If suffixMatch’s start is suffixRange’s start, return potentialMatch.
-
To advance a range range’s start to the next non-whitespace position follow the steps:
-
While range is not collapsed:
-
Let node be range’s start node.
-
Let offset be range’s start offset.
-
If node is part of a non-searchable subtree then:
-
Set range’s start node to the next node, in shadow-including tree order, that isn’t a shadow-including descendant of node.
-
-
If node is not a visible text node:
-
Set range’s start node to the next node, in shadow-including tree order.
-
-
If the substring data of node at offset offset and count 6 is equal to the string " " then:
-
Add 6 to range’s start offset.
-
-
Otherwise, if the substring data of node at offset offset and count 5 is equal to the string " " then:
-
Add 5 to range’s start offset.
-
-
Otherwise:
-
Let cp be the code point at the offset index in node’s data.
-
If cp does not have the White_Space property set, return.
-
Add 1 to range’s start offset.
-
-
If range’s start offset is equal to node’s length, set range’s start node to the next node in shadow-including tree order.
-
To find a string in range for a string query in a given range range, run these steps:
The basic premise of this algorithm is to walk all searchable text nodes within a block, collecting them into a list. The list is then concatenated into a single string in which we can search, using the node list to determine offsets with a node so we can return a range.
Collection breaks when we hit a block node, e.g. searching over this tree:
<div> a<em>b</em>c<div>d</div>e </div>
Will perform a search on "abc", then on "d", then on "e".
Thus, query will only match text that is continuous (i.e. uninterrupted by a block-level container) within a single block-level container.
-
While searchRange is not collapsed:
-
Let curNode be searchRange’s start node.
-
If curNode is part of a non-searchable subtree:
-
Set searchRange’s start node to the next node, in shadow-including tree order, that isn’t a shadow-including descendant of curNode.
-
-
If curNode is not a visible text node:
-
Set searchRange’s start node to the next node, in shadow-including tree order.
-
-
Otherwise:
-
Let blockAncestor be the nearest block ancestor of curNode.
-
While curNode is a shadow-including descendant of blockAncestor and it does not follow searchRange’s end node:
-
If curNode has block-level display then break.
-
If curNode is search invisible:
-
Set curNode to the next node in shadow-including tree order whose ancestor is not curNode.
-
-
If curNode is a visible text node then append it to textNodeList.
-
Set curNode to the next node in shadow-including tree order.
-
-
Run the find a range from a node list steps given query, searchRange, and textNodeList, as input. If the resulting range is not null, then return it.
-
Assert: curNode follows searchRange’s start node.
-
Set searchRange’s start to the boundary point (curNode, 0).
-
-
-
Return null.
A node is search invisible if it is in the HTML namespace and meets any of the following conditions:
-
The computed value of its display property is none.
-
If the node serializes as void.
-
Is any of the following types:
HTMLIFrameElement
,HTMLImageElement
,HTMLMeterElement
,HTMLObjectElement
,HTMLProgressElement
,HTMLStyleElement
,HTMLScriptElement
,HTMLVideoElement
,HTMLAudioElement
-
Is a
select
element whosemultiple
content attribute is absent.
A node is part of a non-searchable subtree if it is or has an ancestor that is search invisible.
A node is a visible text node if it is a Text
node, the computed value of its visibility property is visible, and it is being rendered.
A node has block-level display if the computed value of its display property is any of block, table, flow-root, grid, flex, list-item.
To find the nearest block ancestor of a node follow the steps:
-
While node is non-null
-
If node is not a
Text
node and it has block-level display then return node. -
Otherwise, set node to node’s parent.
-
-
Return node’s node document's document element.
To find a range from a node list given a search string queryString, a range searchRange, and a list of nodes nodes, follow the steps
See § 3.5.3 Word Boundaries for details and more examples.
-
Let searchBuffer be the concatenation of the data of each item in in nodes.
-
Let searchStart be 0.
-
If the first item in nodes is searchRange’s start node then set searchStart to searchRange’s start offset.
-
Let start and end be boundary points, initially null.
-
Let matchIndex be null.
-
While matchIndex is null
-
Let matchIndex be an integer set to the the index of the first instance of queryString in searchBuffer, starting at searchStart.
-
Let endIx be matchIndex + queryString’s length.
endIx is the index of the last character in the match + 1. -
Set start be the boundary point result of get boundary point at index matchIndex run over nodes with isEnd false.
-
Set end be the boundary point result of get boundary point at index endIx run over nodes with isEnd true.
-
If the substring of searchBuffer starting at matchIndex and of length queryString’s length is not word bounded, given the language from each of start and end’s nodes as the startLocale and endLocale:
-
Let searchStart be matchIndex + 1.
-
Set matchIndex to null.
-
-
-
Let endInset be 0.
-
If the last item in nodes is searchRange’s end node then set endInset to (searchRange’s end node's length − searchRange’s end offset)
endInset is the offset from the last position in the last node in the reverse direction. Alternatively, it is the length of the node that’s not included in the range. -
If matchIndex + queryString’s length is greater than or equal to searchBuffer’s length − endInset return null.
If the match runs past the end of the search range, return null. -
Assert: start and end are non-null, valid boundary points in searchRange.
To get boundary point at index, given an integer index, list of Text
nodes nodes, and a boolean isEnd, follow these steps:
This is a small helper routine used by the steps above to determine which node a given index in the concatenated string belongs to.
isEnd is used to differentiate start and end indices. An end index points to the "one-past-last" character of the matching string. If the match ends at node boundary, we want the end offset to remain within that node, rather than the start of the next node.
-
Let counted be 0.
-
For each curNode of nodes:
-
Let nodeEnd be counted + curNode’s length.
-
If isEnd is true, add 1 to nodeEnd.
-
If nodeEnd is greater than index then:
-
Return the boundary point (curNode, index − counted).
-
-
Increment counted by curNode’s length.
-
-
Return null.
3.5.3. Word Boundaries
A word boundary is as defined in the Unicode text segmentation annex. The Default Word Boundary Specification defines a default set of what constitutes a word boundary, but as the specification mentions, a more sophisticated algorithm should be used based on the locale.
Dictionary-based word bounding should take specific care in locales without a word-separating character. E.g. In English, words are separated by the space character (' '); however, in Japanese there is no character that separates one word from the next. In such cases, and where the alphabet contains fewer than 100 characters, the dictionary must not contain more than 20% of the alphabet as valid, one-letter words.
To determine if a substring of a larger string is word bounded, given a string text, an integer startPosition, number count, and locales startLocale and endLocale, follow these steps:
startLocale and endLocale must be a valid [BCP47] language tag, or the empty string. An empty string indicates that the primary language is unknown.
startPosition and count are assumed to be valid in that they represent a substring within the bounds of text.
In languages with a word separator (e.g. " " space) this is (mostly) straightforward; though there are details covered by the above technical reports such as new lines, hyphenations, quotes, etc.
Some languages do not have such a separator (notably, Chinese/Japanese/Korean). Languages such as these requires dictionaries to determine what a valid word in the given locale is.
-
Using locale startLocale, let left bound be the last word boundary in text that precedes startPositionth code point of text.
A string will always contain at least 2 word boundaries before the first code point and after the last code point of the string. -
If the first code point of text following left bound is not at position startPosition return false.
-
Let endPosition be (startPosition + count − 1).
-
Using locale endLocale, let right bound be the first word boundary in text after the endPositionth code point.
-
If the first code point of text preceding right bound is not at position endPosition return false.
-
Return true.
3.6. Indicating The Text Match
The UA may choose to scroll the text fragment into view as part of the try to scroll to the fragment steps or by some other mechanism; however, it is not required to scroll the match into view.
The UA should visually indicate the matched text in some way such that the user is made aware of the text match, such as with a high-contrast highlight.
The UA should provide to the user some method of dismissing the match, such that the matched text no longer appears visually indicated.
The exact appearance and mechanics of the indication are left as UA-defined. However, the UA must not use the Document’s selection to indicate the text match as doing so could allow attack vectors for content exfiltration.
The UA must not visually indicate any provided context terms.
3.7. Feature Detectability
For feature detectability, we propose adding a new FragmentDirective interface
that is exposed via window.location.fragmentDirective
if the UA
supports the feature.
interface { };
FragmentDirective
We amend the Location
interface to include a fragmentDirective
property:
interface {
Location readonly attribute FragmentDirective ; };
fragmentDirective
4. Generating Text Fragment Directives
This section contains recommendations for UAs automatically generating URLs with a text fragment directive. These recommendations aren’t normative but are provided to ensure generated URLs result in maximally stable and usable URLs.
4.1. Prefer Exact Matching To Range-based
The match text can be provided either as an exact string "text=foo%20bar%20baz" or as a range "text=foo,bar".
UAs should prefer to specify the entire string where practical. This ensures that if the destination page is removed or changed, the intended destination can still be derived from the URL itself.
The first recorded idea of using digital electronics for computing was the 1931 paper "The Use of Thyratrons for High Speed Automatic Counting of Physical Phenomena" by C. E. Wynn-Williams.
We could create a range-based match like so:
https://en.wikipedia.org/wiki/History_of_computing#:~:text=The%20first%20recorded,Williams
Or we could encode the entire sentence using an exact match term:
The range-based match is less stable, meaning that if the page is changed to include another instance of "The first recorded" somewhere earlier in the page, the link will now target an unintended text snippet.
The range-based match is also less useful semantically. If the page is changed to remove the sentence, the user won’t know what the intended target was. In the exact match case, the user can read, or the UA can surface, the text that was being searched for but not found.
Range-based matches can be helpful when the quoted text is excessively long and encoding the entire string would produce an unwieldy URL.
It is recommended that text snippets shorter than 300 characters always be encoded using an exact match. Above this limit, the UA should encode the string as a range-based match.
4.2. Use Context Only When Necessary
Context terms allow the text fragment directive to disambiguate text snippets on a page. However, their use can make the URL more brittle in some cases. Often, the desired string will start or end at an element boundary. The context will therefore exist in an adjacent element. Changes to the page structure could invalidate the text fragment directive since the context and match text may no longer appear to be adjacent.
<div class="section">HEADER</div> <div class="content">Text to quote</div>
We could craft the text fragment directive as follows:
text=HEADER-,Text%20to%20quote
However, suppose the page changes to add a "[edit]" link beside all section headers. This would now break the URL.
Where a text snippet is long enough and unique, a UA should prefer to avoid adding superfluous context terms.
It is recommended that context should be used only if one of the following is true:
- The UA determines the quoted text is ambiguous
- The quoted text contains 3 or fewer words
4.3. Determine If Fragment Id Is Needed
When the UA navigates to a URL containing a text fragment directive, it will fallback to scrolling into view a regular element-id based fragment if it exists and the text fragment isn’t found.
This can be useful to provide a fallback, in case the text in the document changes, invalidating the text fragment directive.
The earliest known tool for use in computation is the Sumerian abacus
By specifying the section that the text appears in, we ensure that, if the text is changed or removed, the user will still be pointed to the relevant section:
However, UAs should take care that the fallback element-id fragment is the correct one:
By the late 1960s, computer systems could perform symbolic algebraic manipulations
The UA should note that, even though the current URL of the page is: https://en.wikipedia.org/wiki/History_of_computing#Early_computation, using #Early_computation as a fallback is inappropriate. If the above sentence is changed or removed, the page will load in the #Early_computation section which could be quite confusing to the user.
If the UA cannot reliably determine an appropriate fragment to fallback to, it should remove the fragment id from the URL:
If a UA chooses not to scroll text fragments into view on navigation (reasons why a UA may make this choice are discussed in § 3.4 Security and Privacy), it must scroll the element-id into view, if provided, regardless of whether a text fragment was matched. Not doing so would allow detecting the text fragment match based on whether the element-id was scrolled.