binding popstate event not working
19,174
Solution 1
Type this into the console
window.onpopstate = function() {alert(1);}; history.pushState({}, '');
then click the back button.
Solution 2
I prefer adding the popstate listener as follows, to prevent overwriting of what's already in window.onpopstate
:
window.addEventListener('popstate', function(){alert(1);});
Author by
mirelon
Updated on June 11, 2022Comments
-
mirelon almost 2 years
I have tried to type this code into the browser's console:
window.onpopstate = function() {alert(1);}
and then click the back button. No alert has shown. Am I doing something wrong? Or is it not allowed to bind popstate event to a page from console?
Using Chrome 24 and Firefox 18
-
James Koss over 7 yearsCan you explain why the added history.pushState() part?
-
nikkumang over 7 years@Phuein the history.pushState() is pushing a new history entry's URL. The browser doesn't care if this is a valid URL, and it doesn't reload the page using the new URL. Since the new URL supplied is empty, the URL in the address bar doesn't change, but when you click the back button the alert is triggered.