My main goal is to capture router change events outside of the NextJS framework, not within it. The application I have developed using NextJS includes some code that operates independently of the NextJS context. This code needs to be able to detect navigation changes. The links in the application are created using the NextJS link component with NextJS Router.
The specific code I want to run is housed in an external JavaScript file that gets loaded in _document.tsx
<script src="assets/scripts/testerTools.js" />
This script loads successfully.
When a navigation change occurs, I need a function to execute. Let's say for now it's just a simple function like:
const runFunction = () => {
console.log("it ran");
}
I've already attempted the following approaches:
window.addEventListener('replaceState', () => {runFunction()});
window.addEventListener('pushState', () => {runFunction()});
window.addEventListener('popState', () => {runFunction()});
navigator.addEventListener('navigate', () => {runFunction()});
Unfortunately, none of these methods work when I follow a NextJS link and the URL in the address bar changes.
Is there an event listener I can use to trigger my function and effectively monitor these changes?
I am currently using Firefox, but I don't believe that should impact the functionality of the code in this scenario.