- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Event when window.location.href changes
I'm writing a Greasemonkey script for a site which at some point modifies location.href .
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.
I've seen other solutions which involve timeouts and polling, but I'd like to avoid that if possible.
- greasemonkey

- 1 For YouTube: javascript - How to detect page navigation on YouTube and modify HTML before page is rendered? - Stack Overflow – user202729 Mar 18, 2020 at 13:21
11 Answers 11
I use this script in my extension "Grab Any Media" and work fine ( like youtube case )
With the latest javascript specification
Compressed with OpenAI

- 1 The only solution that could have worked for youtube: [Report Only] Refused to create a worker from ' youtube.com/sw.js ' because it violates the following Content Security Policy directive: "worker-src 'none'". – Simon Meusel Apr 22, 2018 at 14:15
- 6 Worked out of the box with no trouble for my use case, God bless! It's annoying there's no native event for this yet (popstate did not work for me) but one day! I would use window.addEventListener("load", () => {}) instead of window.onload though :) – Sanchit Batra Mar 9, 2020 at 9:46
- 1 man this is amazing. the smartest solution I've seen to date – Eyal Cohen Feb 7, 2021 at 23:58
- 1 put this in content script but it is not firing. – S. W. G. Mar 24, 2022 at 13:03
- 2 Hello I am new to using MutationObservers and love this solution,its the only one I found that worked sofar for YT redirects. Just wanted to note that you could make it more efficient by moving the if (oldHref != document.location.href) check before your forEach call as you would only need to do the check once. – SShah Apr 30, 2022 at 11:34
popstate event :
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:
- 2 But will the popstate fire before the content is loaded? – user2782001 Mar 23, 2017 at 21:29
- 28 unusable if don't have any control over the piece of code that pushState – Nathan Gouy Feb 5, 2020 at 17:22
- 5 This does not always work, it relies on a popstate event to be fired. For example navigating within youtube it won't trigger, only if you press back or forward in history – TrySpace May 27, 2020 at 8:37
- this assume you have visibility or know if pushState is called.. it won't work everywhere, like comments above state as well – mikey Feb 12, 2021 at 1:05
- If you don't control the callers of history.pushState , then you can instead override history.pushState with a function that delegates to the original function, then calls your listener function. – Ben Hutchison Jan 22 at 13:08
You can't avoid polling, there isn't any event for href change.
Using intervals is quite light anyways if you don't go overboard. Checking the href every 50ms or so will not have any significant effect on performance if you're worried about that.
- 4 @AlexanderMills: fortunately there are these new solutions of popstate and hashchange . – serv-inc Apr 24, 2017 at 20:07
- 2 This is not true. – inf3rno Aug 18, 2018 at 12:42
- @MartinZvarík Even in 2010 it was possible to use the unload event plus a micro or macro task to get the new document loaded. – inf3rno Oct 17, 2018 at 2:06
- 20 Unfortunately this answer is still correct in 2020. popstate only fires when the user uses the forward/back buttons and hashchange only fires for hash changes. Unless you have control over the code that's causing the location to change, you have to poll 🤷♀️ – Rico Kahler Apr 10, 2020 at 20:23
There is a default onhashchange event that you can use.
Documented HERE
And can be used like this:
If the browser doesn't support oldURL and newURL you can bind it like this:

- 21 Hashchange events are only sent if your URL has a part starting with a '#' symbol, normally used for anchor links. Otherwise it won't fire. – Fredrik_Borgstrom Dec 5, 2018 at 9:04
- 1 window.addEventListener("hashchange", funcRef, false); – Bishoy Hanna Mar 9, 2020 at 9:45
Through Jquery , just try
By using javascript :
Refer Document : https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

- 1 Just try it, doesn't work on Firefox. – TGrif Dec 31, 2021 at 21:46
- it's working, use javascript – Praveen Danagoudru Jan 19, 2022 at 14:55
Have you tried beforeUnload? This event fires immediately before the page responds to a navigation request, and this should include the modification of the href.
Beware, however, that your event will fire whenever you navigate away from the page, whether this is because of the script, or somebody clicking on a link. Your real challenge, is detecting the different reasons for the event being fired. (If this is important to your logic)
- 1 I'm not sure if this will work because often the hash changes do no involve a page reload. – samandmoore Aug 19, 2010 at 13:32
- I need access to the new DOM as well, I updated the question to clarify that. – Johan Dahlin Aug 19, 2010 at 13:33
- OK - didn't consider the hash situation - will think about that one. As for being able to access the new DOM, then you are out of luck (as far as accesssing this from an event handler is concerned) as the event will fire before the new DOM has been loaded. You might be able to incorporate the logic into the onload event of the new page, but you may have the same issues with respect to identifying whether you need to carry out the logic for every load of that page. Can you provide some more details about what you are trying to achieve, including page flow? – belugabob Aug 19, 2010 at 13:38
- 1 I just tried accessing the location.href inside the onbeforeunload event handler, and it shows the original url, not the target url. – CMCDragonkai Feb 24, 2017 at 11:42
- Beforeunload can cancel the unloading of the page, so the unload event is better, if you don't want to cancel navigation. – inf3rno Aug 18, 2018 at 12:44
Try this script which will let you run code whenever the URL changes (without a pageload, like an Single Page Application):
based on the answer from "Leonardo Ciaccio", modified code is here: i.e. removed for loop and reassign the Body Element if it is removed

- Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem. – Al Foиce ѫ Jun 17, 2021 at 7:43
- This is a very complete answer! – Oytun Dec 27, 2022 at 16:17
Well there is 2 ways to change the location.href . Either you can write location.href = "y.html" , which reloads the page or can use the history API which does not reload the page. I experimented with the first a lot recently.
If you open a child window and capture the load of the child page from the parent window, then different browsers behave very differently. The only thing that is common, that they remove the old document and add a new one, so for example adding readystatechange or load event handlers to the old document does not have any effect. Most of the browsers remove the event handlers from the window object too, the only exception is Firefox. In Chrome with Karma runner and in Firefox you can capture the new document in the loading readyState if you use unload + next tick . So you can add for example a load event handler or a readystatechange event handler or just log that the browser is loading a page with a new URI. In Chrome with manual testing (probably GreaseMonkey too) and in Opera, PhantomJS, IE10, IE11 you cannot capture the new document in the loading state. In those browsers the unload + next tick calls the callback a few hundred msecs later than the load event of the page fires. The delay is typically 100 to 300 msecs, but opera simetime makes a 750 msec delay for next tick, which is scary. So if you want a consistent result in all browsers, then you do what you want to after the load event, but there is no guarantee the location won't be overridden before that.
If you run your script only in Firefox, then you can use a simplified version and capture the document in a loading state, so for example a script on the loaded page cannot navigate away before you log the URI change:
If we are talking about single page applications which change the hash part of the URI, or use the history API, then you can use the hashchange and the popstate events of the window respectively. Those can capture even if you move in history back and forward until you stay on the same page. The document does not changes by those and the page is not really reloaded.

ReactJS and other SPA applications use the history object
You can listen to window.history updating with the following code:

Also, I found a useful solution with MutationObserver :
MutationObserver API Documantation
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged javascript dom greasemonkey dom-events or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Did any DOS compatibility layers exist for any UNIX-like systems before DOS started to become outmoded?
- Why are Suriname, Belize, and Guinea-Bissau classified as "Small Island Developing States"?
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
- remove package from CTAN
- Is it possible to create a concave light?
- Seeing exoplanets with glare
- How do you get out of a corner when plotting yourself into a corner
- nicematrix: add ttfamily in the last-col
- What sort of strategies would a medieval military use against a fantasy giant?
- What Is the Difference Between 'Man' And 'Son of Man' in Num 23:19?
- Counting Letters in a String
- Can archive.org's Wayback Machine ignore some query terms?
- Largest Binary Area
- Bulk update symbol size units from mm to map units in rule-based symbology
- What video game is Charlie playing in Poker Face S01E07?
- What did Ctrl+NumLock do?
- Disconnect between goals and daily tasks...Is it me, or the industry?
- Latex Table Missing Border Lines
- Where does this (supposedly) Gibson quote come from?
- Acidity of alcohols and basicity of amines
- Calculating probabilities from d6 dice pool (Degenesis rules for botches and triggers)
- About an argument in Famine, Affluence and Morality
- What is a word for the arcane equivalent of a monastery? A place where magic is studied and practiced?
- Using Kolmogorov complexity to measure difficulty of problems?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)
Window: hashchange event
The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
Use the event name in methods like addEventListener() , or set an event handler property.
A HashChangeEvent . Inherits from Event .
Event properties
A string representing the new URL the window is navigating to.
A string representing the previous URL from which the window was navigated.
Event handler aliases
In addition to the Window interface, the event handler property onhashchange is also available on the following targets:
- HTMLBodyElement
- HTMLFrameSetElement
- SVGSVGElement
You can use the hashchange event in an addEventListener method:
Or use the onhashchange event handler property:
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- popstate event
JavaScript - on location changed event / on url changed event

In this short article, we would like to show how in JavaScript detect if page URL ( location object) was changed.
In JavaScript there is no locationchange event, but there are some tricks how to do it.
Quick solution:
Better problem description
With location changed monitoring related are three cases:
- when URL is changed in the browser address bar by the user, the whole page is reloaded and there are executed two operations: unload and load page - it is just opening a new page - we can use onload event to do some stuff (check this article ),
- when location is changed by History API ( pushState , replaceState , popState ) in the source code, the page is not reloaded. In this case, API doesn't provide any locationchange event - it is necessary to trigger some events manually after the operation, e.g. history.pushState(...); callEventLogic(); // event on location change // ... history.popState(...); callEventLogic(); // event on location change // etc.
- when the hash is changed in the URL ( location.hash ), the page is not reloaded. API provides some event to notify that change: window.addEventListener('hashchange', function(){ console.log('onhashchange event occurred!'); }) Note: hashchange event is triggered in both chases: - on change from source code, - on change in the browser address bar by the user.
Summary: it is necessary to add own locationchange event support what is mentioned in second point in above list what was presented in Quick solution too.
Native Advertising
Dirask - we help you to, solve coding problems., ask question..
Event listener on window location changes for SPA?

I was curious if anyone knows how to implement an event listener or mutation observer that can detect when the window location's (or URL change at all) happens specifically on a single page application where page reload does not occur.
I'm writing a Chrome Extension that needs to constantly keep track of when that location property changes, and I'm realllly trying to avoid long polling.
onhashchange , onbeforeunload , and unload do not appear to pick up on these changes.

You're probably looking for the popstate event: https://gomakethings.com/how-to-detect-when-the-browser-url-changes-with-vanilla-js/
popstate didn't appear to work for me. When I go to facebook.com and open dev tools and run:
then click around, no events are fired. They're only fired when I press back or forward on the browser.
About Community

How to detect when the browser URL changes with vanilla JS
Yesterday, we looked at how to update the browser URL without refreshing the page using the history.pushState() method .
Today, let’s look how to detect when the URL changes and do things as a result.
The popstate event
If you use history.pushState() to update the URL, when the user clicks the forward or backward buttons, the URL will change but the UI will not.
You can use the popstate method to detect those URL changes and make UI changes as needed.
Yesterday, we learned that the first property passed into the history.pushState() method is state . You can access that property on the event object.
Moving forwards and backwards through History
You can also move forward and backward through the browser’s history with a few other methods in the History API.
The history.back() method goes back one page, and the history.forward() method goes forward one page.
You can jump forward or backwards more than one page using the history.go() method. Pass in the number of pages to jump. Use a positive number to go forward, and negative number to go backwards.
Browser compatibility
The popstate event, and the back() , forward() , and go() methods all work in all modern browsers, and back to IE 10.
# window.location Cheatsheet
Looking for a site's URL information, then the window.location object is for you! Use its properties to get information on the current page address or use its methods to do some page redirect or refresh 💫
https://www.samanthaming.com/tidbits/?filter=JS#2
- Difference between host vs hostname
- How to change URL properties
- window.location vs location
- window.location.toString
- assign vs replace
- replace vs assign vs href
- Scratch your own itch 👍
- Community Input
# window.location Properties
# difference between host vs hostname.
In my above example, you will notice that host and hostname returns the value. So why do these properties. Well, it has do with the port number. Let's take a look.
URL without Port
https://www.samanthaming.com
URL with Port
https://www.samanthaming.com:8080
So host will include the port number, whereas hostname will only return the host name.
# How to change URL properties
Not only can you call these location properties to retrieve the URL information. You can use it to set new properties and change the URL. Let's see what I mean.
Here's the complete list of properties that you can change:
The only property you can't set is window.location.origin . This property is read-only.

# Location Object
The window.location returns a Location object. Which gives you information about the current location of the page. But you can also access the Location object in several ways.
The reason we can do this is because these are global variables in our browser.

# window.location vs location
All 4 of these properties point at the same Location object. I personally prefer window.location and would actually avoid using location . Mainly because location reads more like a generic term and someone might accidentally name their variable that, which would override the global variable. Take for example:
I think that most developer is aware that window is a global variable. So you're less likely to cause confusion. To be honest, I had no idea location was a global variable until I wrote this post 😅. So my recommendation is to be more explicit and use window.location instead 👍
Here's my personal order of preference:
Of course, this is just my preference. You're the expert of your codebase, there is no best way, the best way is always the one that works best for you and your team 🤓
# window.location Methods
# window.location.tostring.
This method returns the USVString of the URL. It is a read-only version of Location.href
In other words, you can use it to get the href value from the
on this 😊. But I did find a performance test on the difference.
JSPerf: Location toString vs Location href
One thing I want to note about these speed tests is that it is browser specific. Different browser and versions will render different outcome. I'm using Chrome, so the href came out faster then the rest. So that's one I'll use. Also I think it reads more explicit then toString() . It is very obvious that href will provide the URL whereas toString seems like something it being converted to a string 😅
# assign vs replace
Both of these methods will help you redirect or navigate to another URL. The difference is assign will save your current page in history, so your user can use the "back" button to navigate to it. Whereas with replace method, it doesn't save it. Confused? No problem, I was too. Let's walk through an example.
Current Page
I just need to emphasize the "current page" in the definition. It is the page right before you call assign or replace .
# How to Do a Page Redirect
By now, you know we can change the properties of the window.location by assigning a value using = . Similarly, there are methods we can access to do some actions. So in regards to "how to redirect to another page", well there are 3 ways.
# replace vs assign vs href
All three does redirect, the difference has to do with browser history. href and assign are the same here. It will save your current page in history, whereas replace won't. So if you prefer creating an experience where the navigation can't press back to the originating page, then use replace 👍
So the question now is href vs assign . I guess this will come to personal preference. I like the assign better because it's a method so it feels like I'm performing some action. Also there's an added bonus of it being easier to test. I've been writing a lot of Jest tests, so by using a method, it makes it way easier to mock.
But for that that are rooting for href to do a page redirect. I found a performance test and running in my version of Chrome, it was faster. Again performance test ranges with browser and different versions, it may be faster now, but perhaps in future browsers, the places might be swapped.
JSPerf: href vs assign
# Scratch your own itch 👍
Okay, a bit of a tangent and give you a glimpse of how this cheatsheet came to be. I was googling how to redirect to another page and encountered the window.location object. Sometimes I feel a developer is a journalist or detective - there's a lot of digging and combing through multiple sources for you to gather all the information available. Honestly, I was overwhelmed with the materials out there, they all covered different pieces, but I just wanted a single source. I couldn't find much, so I thought, I'll cover this in a tidbit cheatsheet! Scratch your own itch I always say 👍
# Community Input
: This is awesome, I’ve used window.location.href in the past, but didn’t realise how simple it is to access sections of the URL!
If you want to see a live-action of what James is talking about, check out the table of content at the top of this article. Click on it and it will scroll down to the specific section of the page.
# Resources
- Share to Twitter Twitter
- Share to Facebook Facebook
- Share to LinkedIn LinkedIn
- Share to Reddit Reddit
- Share to Hacker News Hacker News
- Email Email
Related Tidbits
Console.table to display data, colorful console message, window.location cheatsheet, fresh tidbits.

HTML abbr Tag

How to Pad a String with padStart and padEnd in JavaScript

Avoid Empty Class in Vue with Null

Fix Text Overlap with CSS white-space

How to Check if Object is Empty in JavaScript
JS Reference
Html events, html objects, other references, onhashchange event.
Call a function when the anchor part has been changed:
More "Try it Yourself" examples below.
Definition and Usage
The onhashchange event occurs when there has been changes to the anchor part (begins with a '#' symbol) of the current URL.
An example of what an anchor part actually is: Assume that the current URL is http://www.example.com/test.htm#part2 - The anchor part of this URL would be #part2.
To invoke this event, you can:
- Change the anchor part by setting the location.hash or location.href property of the Location Object
- Navigate to the current page with a different bookmark (Use the "back" or "forward" buttons)
- Click on a link to a bookmark anchor
Browser Support
The numbers in the table specify the first browser version that fully supports the event.
Advertisement
In JavaScript:
In JavaScript, using the addEventListener() method:
Technical Details
More examples.
How to assign the "onhashchange" event to the window object:

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.

IMAGES
VIDEO
COMMENTS
How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page?
The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the
JavaScript : Event when window.location.href changes [ Gift : Animated Search Engine : https://bit.ly/AnimSearch ] JavaScript : Event when
In JavaScript there is no locationchange event,... ... window.addEventListener('locationchange', function(){. console.log('onlocationchange event occurred!
If your content script is loading on every page, add the event listener outside the function which checks the location once it fires. document.
I was curious if anyone knows how to implement an event listener or mutation observer that can detect when the window location's (or URL
window.addEventListener('popstate', function (event) {
The window.location object can be used to get information on the current page address (URL). You can also use its method to do a page redirect or refresh...
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
Change the anchor part by setting the location.hash or location.href property of the Location Object · Navigate to the current page with a different bookmark (