Last active
April 11, 2021 21:02
-
-
Save Xvezda/55cefb76e546c233eb72e42748ba1521 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==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