binding popstate event not working
Asked Answered
T

2

10

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

Triclinic answered 7/2, 2013 at 10:9 Comment(0)
P
20

Type this into the console

window.onpopstate = function() {alert(1);}; history.pushState({}, '');

then click the back button.

Potentiate answered 8/2, 2013 at 4:7 Comment(2)
Can you explain why the added history.pushState() part?Bukharin
@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.Extinctive
R
11

I prefer adding the popstate listener as follows, to prevent overwriting of what's already in window.onpopstate:

window.addEventListener('popstate', function(){alert(1);});
Romanov answered 2/6, 2017 at 0:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.