Get the text fragment part of current URL from window.location

Viewed 306

I wanted to have a custom layout for anyone visitsing my website with text fragment link.

eg. https://en.wikipedia.org/w/index.php?title=Cat&oldid=916388819#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats

Here the part after :~: will be the text fragment. I wanted to get that part.

I have tried window.location.href and window.location.hash. But window.location.href returns just the url without text fragment while window.location.hash returns an empty string.

To replicate this visit this https://en.wikipedia.org/w/index.php?title=Cat&oldid=916388819#:~:text=Claws-,Like%20almost,the%20Felidae%2C,-cats by copying and pasting it to new tab, and try getting the text fragment from window.location (markdown link seems to have problem with text fragment).

So is there any other way to get the text fragment part in address bar ?

2 Answers

You can get the text fragment via performance.getEntriesByType("navigation")[0].name (you can run a regular expression to get the actual value, like performance.getEntriesByType("navigation")[0].name.split('#:~:text=')[1] [but you probably want to make this more forgiving and error-resistent]).

It's currently different based on browser.

Firefox

window.location.href and window.location.hash work as they have worked since the dawn of Javascript and behave exactly as you would expect.

Chrome

Recent changes have modified fragment behavior. Chrome will now remove parts of the URL if :~: appears in the URL.

As @DenverCoder9 pointed out, the only guaranteed way to get the whole URL, what should be a simple task, is now only accomplishable in Chrome via the performance API, performance.getEntriesByType("navigation")[0].name. This task that used to be accomplishable via window.location.href, window.location.hash, and document.URL is no longer possible without this gotcha.

We hope Chrome's new behavior, requiring performance.getEntriesByType("navigation")[0].name compared to window.location.href, is reverted back. This new behavior of "removing parts of the URL" is unprecedented and we consider it harmful.

Worse, if using protocol file://, there is no way to get the URL as performance will not report the URL.

Related, see issues:

Keywords: "text fragments", "fragment directives"

Related