Event When Window.Location.Href Changes

Event when window.location.href changes

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:

window.addEventListener('popstate', listener);

const pushUrl = (href) => {
history.pushState({}, '', href);
window.dispatchEvent(new Event('popstate'));
};

onchange event on window.location.href

You said 'something like', given the example code you're probably looking for the onbeforeunload event handler.

From the Mozilla docs:

window.onbeforeunload = function(e) {
return 'Dialog text here.';
};

Is it possible to capture the window.location.replace event?

window.location.replace acts like a redirection, so you can listen for the BeforeUnload event

The Location.replace() method replaces the current resource with the
one at the provided URL

( don't know why it can't replace the window.location in the snippet :P but it'll work outside it )

document.querySelector('#myBtn').addEventListener('click', function(){  window.location.replace("?one=1&two=2")});
window.addEventListener("beforeunload", function (event) {
console.log(window.location.href); // capture the url event.preventDefault(); // just to pause and see the condole });
<button id="myBtn">Click me</button>

On location.href redirect to # parameter execute code

Use the onhashchange event handler (MDN):

window.onhashchange = function () {
header.classList.remove("sticky");
};

DOM of new page inaccessible after window.location.href value changes

For future ref., it seems all content and attached resources are removed on page reload/redirect.

Another similar query: set timeouts invalidated by page reload

Resources:
MDN window event - unload

HTMX - window.location.href returns previous URL link

HTMX emits the htmx:pushedIntoHistory event after it pushed the new URL to the history. You can attach an event listener to it by:

htmx.on("htmx:pushedIntoHistory", function(event) {
console.log(window.location.href)
})


Related Topics



Leave a reply



Submit