Last active
June 30, 2023 12:23
-
-
Save x0a/a78f6cebe3356c35a44e88b371f3a03a to your computer and use it in GitHub Desktop.
Lightweight beforescriptexecute / onbeforescriptexecute polyfill
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
(function(){ | |
if("onbeforescriptexecute" in document) return; // Already natively supported | |
let scriptWatcher = new MutationObserver(mutations => { | |
for(let mutation of mutations){ | |
for(let node of mutation.addedNodes){ | |
if(node.tagName === "SCRIPT"){ | |
let syntheticEvent = new CustomEvent("beforescriptexecute", { | |
detail: node, | |
cancelable: true | |
}) | |
// .dispatchEvent will execute the event synchrously, | |
// and return false if .preventDefault() is called | |
if(!document.dispatchEvent(syntheticEvent)){ | |
node.remove(); | |
} | |
} | |
} | |
} | |
}) | |
scriptWatcher.observe(document, { | |
childList: true, | |
subtree: true | |
}) | |
})() |
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
document.addEventListener("beforescriptexecute", event => { | |
// There's no efficient way to set event.target | |
// Other polyfills try to accomplish this through hacky means like | |
// replacing the addEventListener prototype. | |
// Instead, we pass the element through the sanctioned event.details property. | |
// | |
// So if the event came from our polyfill, our target will be in event.details. | |
// If it's a native event, it will be in event.target | |
// Nice, clean, simple. | |
let script = event.details || event.target; | |
if(script.textContent.contains("function dontExecuteThisFunction(please)")){ | |
event.preventDefault(); | |
// Now the script won't execute. | |
// Use document.createElement("script") to inject replacement script here, if you want. | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
let script = event.details || event.target;
its need to be event.detail without "s"
and
script.textContent.contains
need to be includes not contains
Besides, the solution is ingenious
I implemented it with very slight modifications to avoid css tag link
From loading to page