Reputation: 1608
i`ve a html document and load a script inside it like that:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
</body>
</html>
My question is, if there is a way to block the script call from the origin code.jquery.com
by adding a script before it which scans it and block it then.
I didn't find anything about it.
Hope you can help me.
Thanks in advance!
Upvotes: 0
Views: 2992
Reputation: 3654
You can prevent script from running using the following functions that I wrote.
blockScript
will loop through all script tags and remove any script tag's source that includes the origin that you provide. Please note that this uses includes API and it will remove all matching script tags.
function blockScript(origin) {
const scripts = Array.from(document.getElementsByTagName("SCRIPT"));
if (scripts.length > 0) {
scripts.forEach((script) => {
if (script.src.includes(origin)) {
document.head.removeChild(script);
}
})
}
}
And using MutationObserver, you can watch for DOM changes.
const observer = new MutationObserver((mutationsList, observer) => {
for(let mutation of mutationsList) {
const addedNodes = Array.from(mutation.addedNodes);
if (addedNodes && addedNodes.some(n => n.nodeName === 'SCRIPT')) {
blockScript('code.jquery.com');
}
observer.disconnect();
}
});
observer.observe(document, { childList: true, subtree: true });
And put everything together ...
<script>
function blockScript(origin) {
const scripts = Array.from(document.getElementsByTagName("SCRIPT"));
if (scripts.length > 0) {
scripts.forEach((script) => {
if (script.src.includes(origin)) {
document.head.removeChild(script);
}
})
}
}
</script>
<script>
const observer = new MutationObserver((mutationsList, observer) => {
for(let mutation of mutationsList) {
const addedNodes = Array.from(mutation.addedNodes);
if (addedNodes && addedNodes.some(n => n.nodeName === 'SCRIPT')) {
blockScript('code.jquery.com');
}
observer.disconnect();
}
});
observer.observe(document, { childList: true, subtree: true });
</script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous" ></script>
<script>
$(document).ready(function() {
console.log('I am undefined');
})
</script>
You should get
Uncaught ReferenceError: $ is not defined
I've only tested this using Chrome.
Upvotes: 2