Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an event that fires when URL changes

Is there an event that fires when ANY part of the URL changes?

Detecting URL changes has been asked many times, but the general answers are outdated (~2010).

Summary of existing answers:

  • You can use popstate for some situations (it does fire for all URL changes).

  • You can use onbeforeunload when a page is being navigated away (and unloading its resources).

  • You can use the hashchange event to watch for hash fragment changes.

  • Otherwise it seems the conventional answer is still to poll for a change to window.location.

Is polling still the best solution in 2016? It's surprising that there isn't an event for this given the other advancements in location and its APIs, so that's why I'm posting this question.

like image 507
Don P Avatar asked Jul 29 '16 21:07

Don P


Video Answer


1 Answers

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'));
};
like image 163
Mohammad Fared Avatar answered Sep 27 '22 22:09

Mohammad Fared