• 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.

newenglander's user avatar

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

Leonardo Ciaccio's user avatar

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:

PHF's user avatar

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.

Tatu Ulmanen's user avatar

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:

iSkore's user avatar

Through Jquery , just try

By using javascript :

Refer Document : https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Praveen Danagoudru's user avatar

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)

belugabob's user avatar

Try this script which will let you run code whenever the URL changes (without a pageload, like an Single Page Application):

d-_-b's user avatar

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

Chester Fung's user avatar

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.

inf3rno's user avatar

ReactJS and other SPA applications use the history object

You can listen to window.history updating with the following code:

job.js.org's user avatar

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 .

Hot Network Questions

window location change event listener

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 .

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:

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.

JavaScript - on location changed event / on url changed event

window location change event listener

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:

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?

window location change event listener

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.

' src=

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

Subreddit Icon

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

# 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 change event listener

# 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

Related Tidbits

Console.table to display data, colorful console message, window.location cheatsheet, fresh tidbits.

Code snippet on HTML abbr Tag

HTML abbr Tag

Code snippet on How to Pad a String with padStart and padEnd in JavaScript

How to Pad a String with padStart and padEnd in JavaScript

Code snippet on Avoid Empty Class in Vue with Null

Avoid Empty Class in Vue with Null

Code snippet on Fix Text Overlap with CSS white-space

Fix Text Overlap with CSS white-space

Code snippet on How to Check if Object is Empty in JavaScript

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:

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:

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

window location change event listener

Get certified by completing a course today!

Subscribe

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

  1. How To Handle DOM and Window Events with React

    window location change event listener

  2. [Released] uSignal

    window location change event listener

  3. SWING

    window location change event listener

  4. WebDriver Event Listener For Effective Logging And Reporting

    window location change event listener

  5. Document Vs Window Event Listener

    window location change event listener

  6. Configuring Load Balancing as a Service in Contrail

    window location change event listener

VIDEO

  1. Pong Game in vb.net

  2. JS Class Example Change Event Listener

  3. Adding Event Listeners to a Button

  4. jump off the window

  5. [FNAF ASMR] Monty Plays Gator Golf With You! (Child Listener) [Roleplay]

  6. Elizabeth Rata speaks at the Real Change Event 2022

COMMENTS

  1. Event when window.location.href changes

    How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page?

  2. 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

  3. JavaScript : Event when window.location.href changes

    JavaScript : Event when window.location.href changes [ Gift : Animated Search Engine : https://bit.ly/AnimSearch ] JavaScript : Event when

  4. JavaScript

    In JavaScript there is no locationchange event,... ... window.addEventListener('locationchange', function(){. console.log('onlocationchange event occurred!

  5. Change window content with window.location.href, then manipulate

    If your content script is loading on every page, add the event listener outside the function which checks the location once it fires. document.

  6. 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

  7. How to detect when the browser URL changes with vanilla JS

    window.addEventListener('popstate', function (event) {

  8. window.location Cheatsheet

    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...

  9. JavaScript Window Location

    The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

  10. onhashchange Event

    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 (