Scroll to Fragment Hash seems to be deleted by NextJS #82649
Replies: 3 comments 11 replies
-
Ah this one again, let me search some previous discussions I have had about this feature and the browser. It has some quirks IIRC. |
Beta Was this translation helpful? Give feedback.
-
// in _document.js
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html>
<Head>
<script dangerouslySetInnerHTML={{
__html: `
(function(){
if (location.href.includes('#:~:text=')) {
localStorage.setItem('textFragment', location.href.split('#:~:text=')[1]);
}
})();
`
}} />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
Key takeawayYou’re not losing the hash because of Next.js — it’s Chrome’s Text Fragment API intentionally removing it before JavaScript runs for security. |
Beta Was this translation helpful? Give feedback.
-
As there is no real solution apart from the hack that only works on Chrome, I am closing this as intended and not solvable. ;aybet it is better that way, as getting that fragment is a bit divulging the user's search terms. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
When applying a text fragment search hash (as done by Google AI search) the search is getting executed, but NextJS seems to remove the hash param from the url.
When calling a hash param to use the scroll to text fragment function by adding "#:~:text=" to the url like http://loclhost:3000#:~:text=FooBar to search for FooBar on the page, highlight it and scroll to it as done by Google's AI Search, the highlighting and scrolling is executed, but next seems to remove the hash from the URL. I would like to track these, but at the time of a useEffect, the data is already gone.
I am using Next 15.3.5 with the page router and have that on three separate installations.
Does anyone know anything about this - or how to circumvent this?
Additional information
Details about the feature:
https://chromestatus.com/feature/4733392803332096
Example
https://strange-animals.photography/#:~:text=impressum
Beta Was this translation helpful? Give feedback.
All reactions