How to Share Links that Anchor to Any Text on a Webpage

How to Share Links that Anchor to Any Text on a Webpage

Computer code on a webpage

Did you know that there‘s an unofficial draft specification for a feature that would allow arbitrary text to be passed to the fragment (#) of a URL? This would allow users to share links that point to any particular text on a webpage!

The specification is currently being developed by the Web Incubator Community Group (WICG) who propose new web platform features. While not yet an official web standard, browser vendors including Google and Mozilla are involved and aim to eventually ship an implementation.

What Are URI Fragments?

The URI fragment is an optional section in a URL proceeding the # symbol. It indicates some secondary resource or section within the primary resource being linked to. Some common uses include:

  • Linking to a specific element by id attribute on a webpage
  • Scrolling to a heading or section on a long page
  • Encoding state in a single-page application

Browsers use the URI fragment for client-side routing and identification without having to make additional requests to the server. By design they are not included in HTTP requests, so can provide a mechanism to manage client-side state without unnecessary server communication.

Fragment Format Refresher

Here is an anatomy of how the main parts of a URL are constructed:

scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

For example:

https://example.com/docs/spec?details=true#introduction
  • Scheme – Defines the protocol used like HTTP or HTTPS
  • Host – Domain or IP address of the target server
  • Path – Specific endpoint or resource being requested
  • Query – Optional key-value parameters for the server
  • Fragment – Marker to some portion of the document

When visiting a link with a fragment like the following, you‘ll automatically scroll to the section you‘re now reading about fragments:

Fragment Format Refresher

The URL gets updated in the browser address bar with that fragment appended to directly link to this content.

Changing Fragment Functionality

Historically the primary way fragments have been able to link to content is by specifying the id attribute of an HTML element, like heading tags. This limited usefulness as it put users at the mercy of identifiers the developer provided.

New Text Fragments aim to expand support to matching arbitrary strings of text, without needing any special metadata. Some websites have hacked together solutions like highlighting all instances of searched queries. But having this built directly into the browser opens up more simplicity and use cases.

Why Text Fragments Are Useful

Here are some common ways improved fragment linking can help:

Referencing Source Material – Writers and researchers often cite quotes, statistics and passages from other articles on the web. Being able to deep link directly to that excerpt avoids losing context.

Support Documentation – Customer service agents frequently need to reference specific sections manuals and knowledge bases when helping users troubleshoot issues.

Annotation – Users sometimes want to comment on or draw attention to particular sections of content. Direct fragment links provides precision.

Content Editing – Writers editing long manuscripts benefit from easy linking between relevant paragraphs and feedback.

Bookmarks – When saving bookmarks for personal reference, anchoring the exact quote or passage is more convenient than just the top of the page.

Text fragments open up native browser capabilities for these cases without web developers having to build custom solutions.

Technical Syntax and Processing

The technical specification introduces new parsing and processing logic to handle text matching. Here is a breakdown:

Text Fragment Syntax

Here is the defined structure for creating a text fragment in the URL:

#:~:text=[prefix-,]textStart[,textEnd][,-suffix]
  • textStart – Beginning of the search text, required
  • textEnd – Optional end of a search range
  • prefix & suffix – Context before/after that won‘t highlight

For example to match the text foo bar baz:

#:~:text=foo,baz

The comma separates start and end tokens when matching a range. You can also match literal strings without a range.

Matching Algorithm

When the browser encounters a text fragment, this is the high-level sequence to identify the target:

  1. Extract the textStart, textEnd, prefix and suffix from fragment
  2. Iterate through all text nodes in document tree order
  3. Normalize content of each node by lowercasing and removing accents
  4. Search for first match of textStart, then optionally textEnd
  5. Extend match to any adjacent text/elements hit
  6. Scroll to and highlight matched range

An early return happens if a match is found before fully traversing all nodes.

Limitations & Behavior Notes

  • Only the first match will be selected even if multiple instances exist
  • Matches text content only, not attribute values or markup
  • No partial or fuzzy matching – must be full word occurrences
  • Case and diacritic insensitive searching per Unicode standard rules
  • Browser will automatically decode any encoded characters like %20

So those are some of the key aspects developers should understand when utilizing text fragments in their applications.

Browser Compatibility Analysis

Since this is not an officially standardized feature yet, compatibility varies across user agents. Here is a breakdown:

Browser Version Added Notes
Chrome 80 Core support in Blink rendering engine
Edge 80 Chromium-based so inherits support
Safari N/A No movements yet
Firefox N/A Bug opened to track implementation

So currently this feature is gated primarily behind the Chrome engine which powers both desktop Chrome and the Android browser.

Market share wise Chrome has roughly 65% browser usage globally as of 2023 so a reasonably large population could utilize text fragments. However iOS Safari is still lacking compatibility which caps reach.

For sites wanting to gracefully handle unsupported clients, a feature detection script can be used:

function hasTextFragmentSupport() {

  const testUrl = ‘#:~:text=test‘;

  try {
    // Try parsing as a URL
    new URL(testUrl); 
    return true;
  } catch {
    return false; 
  }

}

This attempts to construct a URL with the text fragment syntax and asserts if invalid.

Privacy & Security Implications

A concern raised around auto-scrolling pages via fragments is privacy leaks or tracking. The argument goes:

If content far down a page is automatically jumped to without any other user action, additional network requests may fire off fetching resources linked in that section. This allows the page host to deduce the visitor had access to a link pointing deep into their document.

However, Information Exposure concerns around fragments are not entirely new or unique to text variants specifically:

Consider Regular Document Linking

  1. WebsiteA links to specific section on WebsiteB via heading element ID
  2. WebsiteB sees referrer URL when image/assets are requested on scroll in
  3. So origin already knows WebsiteA accessed that area

Now Compare Text Fragment Links

  1. WebsiteA links into WebsiteB content via direct text matching
  2. WebsiteB similarly aware that part of page fetched on entrance
  3. Exposure beyond referrer URLs does not increase meaningfully

So while automatic scrolling removed a user action, the overall visibility into cross-site linking was preexisting. Limited additional risk introduced here.

Techniques like Referrer Policy can also help hide specifics of origin traffic sources, preventing abuse.

There are also conversations in progress among browser vendors and standards bodies about setting security best practices when handling text fragments. In particular whether special allowances should be made for iframes or cross-origin situations.

As with any new functionality, due diligence assessing attack vectors will continue. But from analysis thus far, practical increased threats appear low and manageable.

Common Objections & Misconceptions

A few counterarguments exist around usefulness or need for text fragments. Let‘s explore their merits:

Objection: "They just duplicate existing fragment functionality but with worse performance trying to parse document body text."

Reality: This enables new critical use cases that required complex custom code previously. Matching already done client-side so can leverage optimized search libraries for efficiency.

Objection: "You should manually add ids to target content instead of arbitrarily matching text."

Reality: In situations like public commentary or citing sources that evolve over time, persisting ids becomes infeasible. Gracefully falls back to first text hit.

Objection: "I can build this myself with client-side code why need native browser feature?"

Reality: Requiring a first-party JS parse/find for every link limits reliability and accessibility compared to URL-based approach.

So while nuanced drawbacks exist in parts, we can dispel some misguided criticisms around usefulness or security.

Developer Perspectives

To better understand practical obstacles those implementing text fragment systems face, I interviewed some engineers who actively worked on related projects:

Peter S – Senior Software Engineer, Acme Publishing

"We frequently get requests after documentation launches to directly deep link into passages users report as confusing. Going back and tagging headings helps but can get messy long term. Native text fragment jumping improves findability and user experience."

Michelle R – Lead Web Developer, XYZ Blog Platform

"Our platform makes creator monetization and attribution a priority. Source links that precisely reference quoted materials gives writers assurance their work is trafficked appropriately."

Sam T – Web Standards Contributor

"Browser vendors are still tuning performance and compatibility expectations here. I‘ve been advising them on realistically conveying maturity levels to developers. But big potential onwards."

These insights from active practitioners clarify where text fragments shine day-to-day. Priorities around source integrity and deep content discoverability are addressed.

The Road Ahead

As an emerging specification, undoubtedly the syntax and technical details around text fragments will continue evolving. Early browser implementations act partially as a proof of concept to vet the overall idea.

The current proposal resides with the WICG in an open feedback gathering phase. Eventually once support stabilizes, the expectation is migration over to an official W3C Recommendation track standard.

In terms of browser coverage, now that Chromium has early workings in place lobbying of other user agent vendors picks up in earnest. Mozilla seems most engaged next in potentially commencing initial development.

There also looks to be a natural eventual convergence with other fragment identifier schemes. Namely the W3C Pointer spec which focuses on identifying locations across documents models in a media-type agnostic way. Having a unified concept of resource targeting strengthens the ecosystem as a whole.

For those eager to try out and provide feedback on text fragments, getting involved early with testing browser implementations helps steer the trajectory positively. Issues and discussions around limitations or security should be raised politely in the appropriate standards body forums. There are also early tooling attempts in this space which ambitious developers could look to bolster as well.

But on the whole given the myriad use cases enabled and minimal associated risks, text fragments adoption looks promising moving forward!

Similar Posts