Guide on detecting and capturing a change in location history event

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.

Answer №1

If you're seeking a method to detect Next.js router transitions outside of the framework itself, there is a solution using JavaScript. By utilizing the window.onpopstate event handler, you can monitor changes to the browser's address bar without relying on Next.js router object.

Follow these steps to implement window.onpopstate for tracking router changes independently:

// Set up event listener for popstate
window.onpopstate = (event) => {
  // Use event.state or document.location.href to access the new URL
  const newURL = event.state || document.location.href;
  
  console.log('Detected router change:', newURL);

  // Execute custom function
  runFunction();
};

// Define your custom function
const runFunction = () => {
  console.log('Custom function executed');
  // Add your custom logic here
};

By establishing this event listener, you can capture all history changes in the browser, including those initiated by Next.js router updates, navigation button clicks, or manual URL alterations.

This approach enables you to manage router transitions independently from Next.js internal routing system, suitable for monitoring all router modifications across your application, not just within specific Next.js components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building a bespoke search input for the DataTables JQuery extension

As the title indicates, I am in the process of developing a custom search box for the DataTables JQuery plugin. The default options do not suit my needs, and configuring the DOM is also not ideal as I aim to integrate it within a table row for display purp ...

Setting up TLS for NextJS based applications with @improbable-eng/grpc-web

Currently, in the process of developing my web application using NextJS, I have incorporated https://github.com/improbable-eng/grpc-web for facilitating communication between frontend and backend. The React element below exemplifies the utilization of grpc ...

Retrieve the associative array from the user input by utilizing jQuery

How can I create an associative array from a form containing multiple text inputs using jQuery (or directly in JS)? Here's an example of the form: <form> <input type="text" name="name[13]" value="test 1" /> <input type="text" name="nam ...

Having trouble with Tailwindcss in my Next.js App during the build process

I am currently in the process of developing a Chrome Extension using Nextjs. For guidance, I referred to an informative article at this link During testing in dev mode (npm run dev), everything related to tailwindcss functioned correctly. However, upon ...

Display Issue with Header Row in React Data Table Component - Full Text Not Visible

Hey there! I've been working with a neat npm package called react-data-table-component. However, I've run into a bit of trouble trying to adjust the width of the table header text. Take a look at the issue here: https://i.sstatic.net/AzqNw.png ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...

How can one identify a concealed glitch that exclusively occurs for a particular individual or hardware in a React environment?

Is it possible to identify a bug that occurs only with a particular individual or hardware in a React application? This bug is invisible and never appears during tests, but only manifests with a specific client within my company. Do you have any tips on h ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

What is the best way to arrange this object alphabetically by name using Angular?

My client is in need of an AngularJS application that will interact with an API from an existing app. The API returns JSON data structured like the following: { "groups":{ "60":{ "name":"History" }, "74":{ "n ...

Extract all links from an external website

I'm attempting to extract all the URLs from a webpage using jQuery so that I can later use them with $.get(). If these URLs were located on the same page as the script, retrieving them would be easy by doing something like var links = document.getEle ...

What is the function of '@' symbol in coding?... obtain {ModuleName} from '@ModuleName'

What is the significance of the '@' symbol in imports? I've noticed that various modules like '@react-navigation', '@babel', and others use the '@' symbol. Does this symbol serve a specific purpose, or is it s ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

Find the line containing the selected text within a JavaScript code

I am working on a contentEditable div where users can enter multi-line text. I need to be able to inspect the line that the user is currently typing in when they press enter. Is there a way to retrieve the context of that specific line (or all lines)? Is ...

Navigating to the parent Vue component in a Vue3 project with Composition API structure in WebStorm

After transitioning to Vue3 and embracing the Composition API style, I find myself missing a small convenience that I had when developing in the previous Options API pattern. In WebStorm/IntelliJ IDE, I used to be able to command-click (Mac) on the "export ...

Is it possible to dynamically change the color of a box shadow using an event handler?

I'm currently in the process of developing an application that consists of six distinct topics organized within a flexbox structure, complete with a box-shadow effect. My objective is to dynamically alter the color of the box-shadow through an event ...

Executing secure journey within TypeScript

Just came across an enlightening article on Medium by Gidi Meir Morris titled Utilizing ES6's Proxy for secure Object property access. The concept is intriguing and I decided to implement it in my Typescript project for handling optional nested object ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Tips for ensuring a webpage loads at a specific resolution

I recently created a website on my computer with a screen resolution of 1920x1020. However, when I view it on other machines with a 1366x768 resolution, the website appears distorted. Is there a way to set a fixed resolution for my website to ensure it l ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...