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
Add a "Hook" to All Ajax Requests on a Page
How to Load Data from a CSV File in D3 V5
Why Do Results Vary Based on Curly Brace Placement
Input Type=File Show Only Button
How to Access the Contents of an Svg File in an <Img> Element
How to Add Drop-Down List (<Select>) Programmatically
How to Find a Parent with a Known Class in Jquery
Jquery (Almost) Equivalent of PHP's Strip_Tags()
Vue.Js Get Selected Option on @Change
How to Sort an Array of Objects with Jquery or JavaScript
Why Does JavaScript Object Show Different Values in Console in Chrome, Firefox, Safari
How to Update an "Array of Objects" with Firestore
Image Loaded Event in for Ng-Src in Angularjs
Drop-Down Box Dependent on the Option Selected in Another Drop-Down Box
JavaScript - Head, Body or Jquery