Rayrun

Web's Most Underutilized API: Text Fragments

We delve into the untapped potential of text fragments, a little-known but powerful browser feature that allows users to link directly to specific sentences within a web page. As we unravel its working and provide a guide on how to implement it, we aim to spark interest and facilitate its wider adoption in website design.
  1. Introduction to Text Fragments
    1. Beyond a Simple URL: Narrowing Down Text Selection
      1. The Hurdle to Widespread Adoption: Lack of Native Browser Support
        1. Enabling Text Fragment Generation on Your Website
          1. Text Fragments in the Wild
            1. Text Fragments for Accessibility
              1. The state of Text Fragments in Browsers
                1. Styling Text Fragments
                  1. Anchor Links vs Text Fragments
                    1. Anchor Links
                      1. Text Fragments
                      2. Conclusion: The Hope for More Adoption of Text Fragments
                        1. Further Reading

                          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]

                          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));
                          });

                          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).

                          Text Fragments for Accessibility

                          Text fragments can improve web accessibility in several ways:

                          1. Specific Referencing: Text fragments allow for the direct highlighting of specific pieces of content. This can be incredibly useful for people using assistive technologies, such as screen readers, as it enables them to directly access the relevant section of content without having to navigate through the entire page.
                          2. Content Contextualization: By using text fragments, users are able to provide more context when sharing links, which can assist those who rely on contextual information to understand the content.
                          3. Improved Navigation: They can also help improve navigation within a page. For example, if a page doesn't have a proper heading structure or lacks a table of contents, text fragments can serve as an alternative way of guiding users to specific sections.
                          4. Efficient Reading: For users with cognitive or visual impairments who might find reading a long article challenging, text fragments allow them to go directly to the most relevant part, saving time and reducing cognitive load.
                          5. Helpful for User Testing and Feedback: Text fragments can be used when testing accessibility or providing feedback on specific web content, making it clear exactly which part of the page is being referred to.

                          The state of Text Fragments in Browsers

                          The good news is that over 85% of browsers support text fragments.

                          https://caniuse.com/mdn-html_elements_a_text_fragments

                          Firefox is the only major browser that doesn't support text fragments. However, it's not a big deal because Firefox users can still use text fragments by installing a polyfill.

                          You may follow this discussion to track the progress of Firefox's implementation of text fragments: https://github.com/mozilla/standards-positions/issues/194

                          Styling Text Fragments

                          You can also style text fragments using the ::target-text pseudo-element.

                          ::target-text {
                            background-color: yellow;
                          }

                          Text Fragments must not be confused with anchor links. Anchor links are used to direct users to a specific part of a webpage. However, they are not as precise as text fragments. For example, if you want to direct a user to a specific sentence within a paragraph, you can't do that with anchor links. Instead, you can only direct them to the paragraph itself.

                          An anchor link (also known as a fragment identifier) is a type of hyperlink that leads to a specific part of a webpage. Web developers create these links by adding an "id" attribute to an HTML element on the page. Once this attribute is added, a user can link directly to that element by appending a hash (#) and the id value to the end of the URL.

                          For example, if there's an element <div id="section2">...</div> on a webpage, one could link directly to it with a URL like https://ray.run/blog/webs-most-underutilized-api-text-fragments#introduction-to-text-fragments#introduction-to-text-fragments.

                          One key limitation of anchor links is that they require the website's developer to anticipate which sections of the page a user might want to link to and add appropriate ids.

                          Text Fragments

                          Introduced much more recently, text fragments allow a user to link to any part of a webpage simply by specifying some of the text at that part of the page. The URL syntax for a text fragment looks something like this: https://ray.run/blog/webs-most-underutilized-api-text-fragments#:~:text=as%20someone%20who%20frequently%20takes%20notes.

                          Unlike with anchor links, creating a text fragment link doesn't require the website's developer to do anything. Any user can create a text fragment link to any webpage, without needing any specific HTML markup to be present on the page.

                          In summary, while both anchor links and text fragments allow for linking to specific parts of webpages, anchor links require forethought and action by the website's developer, while text fragments can be created by any user, linking to any part of any webpage.

                          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:

                          Thank you!
                          Was this helpful?

                          Now check your email!

                          To complete the signup, click the confirmation link in your inbox.

                          Subscribe to newsletter

                          You will receive a weekly email with the latest posts and QA jobs.

                          TwitterGitHubLinkedIn
                          AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

                          Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].