DEV Community

Luc Gagan
Luc Gagan

Posted on • Originally published at ray.run

Web's Most Underutilized API: Text Fragments

Introduction to Text Fragments

As someone who frequently takes notes, I was excited when text fragments were introduced to browsers about four years ago. I anticipated the widespread adoption of this feature across websites and blogs. However, to my disappointment, this never happened. Today, I aim to rekindle this idea by illustrating the usefulness of text fragments.

To begin, let's look at an example:

https://ray.run/blog/playwright-mobile-app-testing-for-android-a-comprehensive-guide#:~:text=the%20android%20support%20in%20playwright%20is%20experimental%20and%20hence%2C%20comes%20with%20a%20few%20limitations

This URL contains a text fragment, directing you directly to a specific sentence within an article—in this case, my blog post about Playwright testing. However, this feature can be applied to any website, e.g. GitHub

https://github.com/microsoft/playwright#:~:text=Playwright%20is%20a%20framework%20for%20Web%20Testing%20and%20Automation

Beyond a Simple URL: Narrowing Down Text Selection

Despite seeming like a simple percent-encoded text fragment within a URL, it's actually facilitated by an ingenious API.

Imagine a situation where you want to highlight a specific instance of a recurring word in an article, like "Playwright". How would the browser know which of the many references you intended to share? Here's how to do it:

https://ray.run/blog/playwright-mobile-app-testing-for-android-a-comprehensive-guide#:~:text=Android%20support%20in-,playwright,-is%20experimental%20and

The text fragment syntax allows you to pinpoint text by specifying the words that surround it. Here's the syntax:

#:~:text=[prefix-,]textStart[,textEnd][,-suffix]
Enter fullscreen mode Exit fullscreen mode

In the provided example, the browser highlights the correct instance of "Playwright" because it looks for it between "Android support in" and "is experimental and".

The Hurdle to Widespread Adoption: Lack of Native Browser Support

However, I believe the lack of widespread adoption of text fragments is due to the absence of native browser support for generating these fragments. It would be beneficial if users could simply select the text and share a link to a specific fragment within an article. In fact, you can try this out for yourself—select any text in this article and observe the URL change.

Enabling Text Fragment Generation on Your Website

Now, you might wonder how I accomplished this. There's a function called generateFragment that's included in the text-fragments-polyfill polyfill utility. However, there's hardly any information about this outside of a single article I've found.

Here's the key code for it:

import { generateFragment } from 'text-fragments-polyfill/dist/fragment-generation-utils.js';

export const generateTextFragment = (selection: Selection): string | null => {
  const result = generateFragment(selection);

  if (result.status !== 0) {
    return null;
  }

  let url = `${location.origin}${location.pathname}${location.search}`;

  const fragment = result.fragment;
  const prefix = fragment.prefix
    ? `${encodeURIComponent(fragment.prefix)}-,`
    : '';
  const suffix = fragment.suffix
    ? `,-${encodeURIComponent(fragment.suffix)}`
    : '';
  const start = encodeURIComponent(fragment.textStart);
  const end = fragment. textEnd ? `,${encodeURIComponent(fragment. textEnd)}` : '';

  url += `#:~:text=${prefix}${start}${end}${suffix}`;

  return url;
};

document.addEventListener('mouseup', () => {
  const selection = window.getSelection();

  if (!selection) {
    return;
  }

  history.replaceState(null, '', generateTextFragment(selection));
});
Enter fullscreen mode Exit fullscreen mode

With this code, visitors to your website can link to any text fragment they want to share.

Text Fragments in the Wild

What's crazy is that I cannot find many usage examples in the wild.

Google uses them for their featured snippets:

https://www.google.com/search?q=how+do+google+featured+snippets+work&oq=how+do+google+featured+s

You see that clicking the link associated with the snippet takes you to:

https://developers.google.com/search/docs/appearance/featured-snippets#:~:text=Featured%20snippets%20are%20special%20boxes,%22People%20Also%20Ask%22).

Conclusion: The Hope for More Adoption of Text Fragments

Text fragments can be used in a variety of scenarios to provide more context and specificity when sharing content. It is a great way to improve the user experience and make it easier for people to share content. With this post, I hope to encourage more people to adopt this feature.

Further Reading

A few resources that I've discovered that discuss text fragments:

Top comments (1)

Collapse
 
kerthin profile image
Roden

Not a bad article, and the topic is good. You are right, text fragments are a convenient thing, but everything, as always, rests on the issue of support for a particular browser. Moreover, at the moment, W3C participants are skeptical about changing the url format. By the way, thank you for the links you provided, and sometimes I'm too lazy to look for everything myself.

This reminds me of the recent update for Safari, where they added very good updates (Web Push, margin-trim), which unfortunately only work in Safari

P.S. I would advise you to use a different format for using links in the future, so as not to insert large links. Like this: [Thomas Steiner Post Link](https://web.dev/i18n/en/text-fragments/) => Thomas Steiner Post Link

Here is a good article on the use of the editor Dev.to: