Javascript

Event when windowlocationhref changes

25 September 2026 · 4 min read

Event when windowlocationhref changes

In the dynamic world of web development, understanding and reacting to user navigation is paramount for creating seamless and interactive experiences. Modern web applications, especially Single Page Applications (SPAs), heavily rely on dynamically changing the URL without full page reloads. This critical process often involves manipulating the browser’s history, but how do developers reliably detect an event when window.location.href changes? Unlike traditional page reloads, direct observation of window.location.href isn’t as straightforward as attaching an onchange listener, because the property itself doesn’t emit events. This guide delves into various robust techniques, from leveraging native browser events to advanced History API overrides, ensuring you can precisely track and respond to every significant URL alteration in your application.

Understanding Window.location.href and Its Dynamics

The window.location.href property represents the entire URL of the current page. While it seems like a simple string, its value can change in several ways, each requiring a different approach for detection. The most obvious way is a full page reload, where the browser navigates to an entirely new URL, effectively destroying the old document and loading a new one. In such cases, the previous JavaScript context is lost, and your scripts start fresh on the new page.

However, the complexity arises with client-side navigation, particularly prevalent in Single Page Applications (SPAs). Here, frameworks like React, Angular, or Vue manipulate the browser’s history programmatically using the History API, specifically methods like pushState() and replaceState(). These methods change the URL displayed in the address bar and modify the browser’s history stack without triggering a full page reload. Additionally, changes to the URL’s hash fragment (e.g., section1) also alter window.location.href without a full refresh.

The core challenge for an event when window.location.href changes detection is that neither pushState() nor replaceState() inherently dispatch events when they are called. This means you cannot simply add an event listener to the window.location object itself to catch these programmatic changes. Developers must employ more sophisticated strategies to ensure their applications remain responsive and synchronize with the displayed URL, whether for analytics, dynamic content loading, or state management.

Leveraging Browser Events for URL Changes

While a direct event for window.location.href changes from History API manipulation doesn’t exist, browsers do provide events for specific types of URL alterations. Understanding these can cover a significant portion of your detection needs.

The hashchange Event

The hashchange event is a straightforward way to detect alterations to the URL’s hash fragment. This event fires whenever the part of the URL after the `` symbol changes. It’s particularly useful for older SPAs or for navigating within a single document, where different sections are identified by hash values.

For example, if a user navigates from example.com/pagesection1 to example.com/pagesection2, the hashchange event will fire. This event object provides oldURL and newURL properties, making it easy to determine what changed. Implementing a listener for this event is quite simple:

window.addEventListener('hashchange', function(event) { console.log('Hash changed!'); console.log('Old URL:', event.oldURL); console.log('New URL:', event.newURL); // Perform actions based on the new hash });

It’s important to note that the hashchange event only fires for hash changes, not for changes to the path or query parameters. For more comprehensive URL detection, especially with modern SPA routing, other methods are required.

The popstate Event

The popstate event is another crucial browser event for detecting an event when window.location.href changes. This event fires when the active history entry changes. This typically occurs when the user navigates through their browser’s history using the back or forward buttons, or when JavaScript programmatically calls history.back(), history.forward(), or history.go().

To detect an event when window.location.href changes due to user navigation (like back/forward button clicks), you should listen for the popstate event. When popstate<b>Question & Answer : </b><br></br><p>I'm writing a Greasemonkey script for a site which at some point modifies location.href.</p> <p>How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page? I also need access to the DOM of the document pointing to the new/modified url.</p> <p>I've seen other solutions which involve timeouts and polling, but I'd like to avoid that if possible.</p><br></br><p>I use this script in my extension "Grab Any Media" and work fine ( <em>like youtube case</em> )</p> <pre class="lang-js prettyprint-override">var oldHref = document.location.href; window.onload = function() { var bodyList = document.querySelector('body'); var observer = new MutationObserver(function(mutations) { if (oldHref != document.location.href) { oldHref = document.location.href; /* Changed ! your code here */ } }); var config = { childList: true, subtree: true }; observer.observe(bodyList, config); }; </pre> <p><strong>With the latest javascript specification</strong></p> <pre>const observeUrlChange = () => { let oldHref = document.location.href; const body = document.querySelector('body'); const observer = new MutationObserver(mutations => { if (oldHref !== document.location.href) { oldHref = document.location.href; /* Changed ! your code here */ } }); observer.observe(body, { childList: true, subtree: true }); }; window.onload = observeUrlChange; </pre>