Menü schliessen
Created: January 27th 2025
Categories: Common Web Development,  IT Development,  IT Knowledge
Author: Miljan Puzovic

Highlight text on page and scroll to it using "URL Text Fragments"

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Have you ever needed to share a specific piece of text from a lengthy web page? Or wanted to direct someone to an exact paragraph without relying on section headings or IDs? URL Text Fragments are here to revolutionize how we navigate and share web content. In this comprehensive guide, we'll explore this powerful feature that allows you to create links that scroll directly to and highlight specific text on any web page.

What are URL Text Fragments?

URL Text Fragments are a powerful web platform feature that extends the capabilities of regular URL fragment identifiers (#). Unlike traditional anchor links that require predefined IDs in the HTML, text fragments allow you to link to any text content on a web page, even if it hasn't been specifically marked up for linking.

When someone clicks a link with a text fragment, the browser automatically:

  • Scrolls to the specified text location on the page
  • Highlights the text in yellow (similar to using the browser's find function)
  • Optionally scrolls to ensure the text is centered in the viewport

Browser Support and Compatibility

Before diving into the implementation details, it's important to understand the current browser support for this feature. Text fragments are supported in Chromium-based browsers (Chrome, Edge, Opera) and are being considered by other browser vendors. You can check the current browser support status at Can I Use: URL Scroll-to-Text Fragment.

Graceful Degradation

One of the best aspects of text fragments is their graceful degradation. In browsers that don't support the feature, the link still works normally - it just won't automatically scroll to the specified text. This makes it safe to use text fragments in production without worrying about breaking the experience for some users.

How to Create Text Fragment Links

The syntax for text fragments follows a specific pattern that allows for precise targeting. Here's the basic structure:

https://example.com#:~:text=[prefix-,]textStart[,textEnd][,-suffix]

Basic Text Fragment

The simplest form of a text fragment link looks like this:

https://example.com#:~:text=exact%20phrase%20to%20match

Here's a real-world example that links directly to the "LEXO Managed Webhosting" text on a webpage:

https://www.lexo.ch/de/software-entwicklung#:~:text=LEXO%20Managed%20Webhosting

When you click this link in a supported browser, it will automatically scroll to and highlight the text "LEXO Managed Webhosting" on the page. This demonstrates how text fragments can be used to direct users to specific content on a webpage, even without traditional anchor tags.

Advanced Syntax Options

For more precise targeting, you can use these advanced features:

  • Range-based selection: Target text between a start and end phrase
  • Context hints: Add prefix and suffix text to ensure uniqueness
  • Multiple fragments: Combine multiple text fragments in one URL

Examples of Advanced Syntax

# Range-based selection
https://example.com#:~:text=start%20phrase,end%20phrase

# With context hints
https://example.com#:~:text=prefix-,target%20phrase,-suffix

# Multiple fragments
https://example.com#:~:text=first%20phrase&text=second%20phrase

For more detailed syntax examples and specifications, you can refer to the official WICG documentation.

Comparison with Other Solutions

Feature Text Fragments Traditional Anchors JavaScript Solutions
Works without page modification Yes No Varies
Highlights target text Yes No Possible
Browser Support Limited Universal Universal
Performance Impact Minimal None Varies

Creating a Simple Text Fragment Generator

To make it easier to create text fragment links, here's a simple JavaScript function that generates properly encoded text fragment URLs:

function createTextFragmentURL(baseURL, textStart, textEnd = '', prefix = '', suffix = '') {
  // Encode the components
  const encodedStart = encodeURIComponent(textStart);
  const encodedEnd = textEnd ? encodeURIComponent(textEnd) : '';
  const encodedPrefix = prefix ? encodeURIComponent(prefix) + '-,' : '';
  const encodedSuffix = suffix ? ',-' + encodeURIComponent(suffix) : '';
  
  // Build the text fragment
  const textFragment = encodedPrefix + encodedStart + 
    (encodedEnd ? ',' + encodedEnd : '') + encodedSuffix;
  
  // Combine with base URL
  return `${baseURL}#:~:text=${textFragment}`;
}

// Example usage
const url = createTextFragmentURL(
  'https://example.com',
  'target text',
  '',
  'before',
  'after'
);

Best Practices and Tips

1. Selecting Text

  • Choose unique text phrases to avoid ambiguous matches
  • Keep selections reasonably short to improve reliability
  • Use context hints (prefix/suffix) for common phrases

2. Error Handling

  • Always test generated links in supported browsers
  • Provide fallback anchor links when possible
  • Consider adding visual indicators for successful matches

3. Performance Considerations

  • Avoid creating extremely long text fragments
  • Limit the number of text fragments in a single URL
  • Consider the impact on page load time

Security and Privacy Considerations

While text fragments are powerful, they come with some important security and privacy considerations:

  • Cross-Origin Restrictions: Text fragments only work on HTTPS pages or same-origin HTTP pages
  • User Consent: Browsers may require user interaction before scrolling to the fragment
  • Privacy Implications: Text fragments could potentially be used for tracking or fingerprinting