JavaScript event listener for history.pushState

2018-01-13 20:14:38 Coding JavaScript

In HTML there is an event onpopstate, but not onpushstate or onalterstate. How can we monitor such state changes? The answer is to alter the history.pushState function and manually dispatch an event inside.

More over, suppose we are writing a Chrome extension which has run_at: "document_start" that aims to capture all changes in states. Then we need to inject a <script> tag into the HTML, and we must do it as early as possible – right after the <head> tag is available. To achieve this we use a MutationObserver.