0

Can I listen to window.location.replace change js?

If a user clicks on a submit button, and a specific function will handle the event(checks/validates and redirects user to another page.)

What I want is to execute a function before redirecting.

I can't edit the validation part.

I have to listen to window.location.href 's change or a command to change it.

Can I know if a page is being redirected and prevent it happening the redirect to run a piece of my code?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Change the part of your code that calls `window.location.replace` to instead call a *different* function, where that other function carries out the checks and *then* calls `window.location.replace` itself – CertainPerformance Jan 29 '20 at 08:45
  • Most of the answer's in this [question](https://stackoverflow.com/questions/6390341/how-to-detect-url-change-in-javascript) said it is possible to listen for hash change event (https://example.com/#/) and this [answer](https://stackoverflow.com/a/52809105/11719787) may be useful to you – Sameer Jan 29 '20 at 08:52
  • What triggers the change? You talked about the click of a submit button, then location.replace is not called, nor is location.href changed, simply a true navigation happens. [You can detect](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onunload) navigation away of the document, but what you can do in this event is quite limited. – Kaiido Jan 29 '20 at 09:04

0 Answers0