2

I'm trying to create a Chrome plugin for facebook and I'm using onpopstate event to check when the user goes to another page. The only problem is that the onpopstate doesn't fire.

This is the (simple) code I'm using:

window.onpopstate = function() { console.log('pop'); };

this is a screen of the problem:

code test in console

As you can see the pushState code is called, but the onpopstate listener is not.

Do you know what's happening here?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
patrick
  • 6,533
  • 7
  • 45
  • 66
  • 1
    Er, ahrm - could you walk me through this.. How is an eventlistener for 'onpopstate' ever going to be called in response to 'push'? Given that you've attached a screen-shot, we can rule out an error when you copied your code to the forum. Is possible you've just had a wtf moment? Roughly equivalent to selecting a forward gear in your car then wondering why it didn't reverse? – enhzflep Oct 29 '12 at 00:41
  • Please check the doc: https://developer.mozilla.org/en-US/docs/DOM/window.onpopstate ;) – patrick Oct 29 '12 at 09:19
  • 2
    You mean the bit that says this? "Note that just calling history.pushState() or history.replaceState() **won't** trigger a popstate event. _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)._" – enhzflep Oct 29 '12 at 10:08
  • 1
    Its gone awfully quiet in here. Did you miss that part of the document? – enhzflep Oct 29 '12 at 16:23
  • Sorry I was offline until now, damn! I checked that document almost three times and I read it always wrong :( Sorry, my mistake! – patrick Oct 29 '12 at 19:11
  • Lol, don't give it a second thought.. :) Happens to the best of us.. I really appreciate your returning to the question. I'd have kept wondering otherwise, probably starting up a *nix box with FF to test it. Cheers. :) – enhzflep Oct 29 '12 at 19:22
  • Your conversation is still appreciated 7 years later – PascalVKooten Mar 26 '19 at 17:52

1 Answers1

0

@enhzflep's answer is in the comments above and not immediately obvious. From MDN:

Calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document.

In other words, the onpopstate event shouldn't be firing in this case.

Max Wallace
  • 3,609
  • 31
  • 42