Skip to content

Instantly share code, notes, and snippets.

@Xvezda
Last active April 11, 2021 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xvezda/55cefb76e546c233eb72e42748ba1521 to your computer and use it in GitHub Desktop.
Save Xvezda/55cefb76e546c233eb72e42748ba1521 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Custom page change event
// @namespace http://xvezda.com/
// @version 0.1
// @description fire event on page changed.
// @author Xvezda
// @match http://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Your code here...
function dispatchEvent() {
var customEvent = new CustomEvent('pagechange');
window.dispatchEvent(customEvent);
}
let timer = null
const debounce = 100
window.addEventListener('load', function (evt) {
dispatchEvent();
history.pushState = new Proxy(history.pushState, {
apply(target, thisArg, argumentsList) {
const [state, title, url] = argumentsList;
window.dispatchEvent(
new CustomEvent('pushstate', {
detail: {
state,
title,
url
}
})
);
return Reflect.apply(target, thisArg, argumentsList);
}
});
function mutateCallback(mutations) {
clearTimeout(timer);
timer = setTimeout(function () {
dispatchEvent();
}, debounce);
}
const observer = new MutationObserver(mutateCallback);
observer.observe(document.body, {
childList: true,
subtree: true,
});
window.addEventListener('popstate', dispatchEvent, false);
window.addEventListener('pushstate', dispatchEvent, false);
}, false);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment