Here is a simple page:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test page</title>
<script type="text/javascript">
function foo (num) {
alert(num);
}
</script>
</head>
<body>
Hello World
<script type="text/javascript">
foo(2);
</script>
</body>
</html>
I'd like to write a Chrome extension to prevent the execute of the bottom script(foo(2)
).
I tried to write a content script which removes the last script tag with:
document.body.removeChild(document.body.lastChild);
but it does not work.
I think this may be because the content script runs after the last script line has executed. then I tried to set the run_at
to document_start
or document_end
, but none of them work for me..
Open Chrome DevTools. Press Control+Shift+P or Command+Shift+P (Mac) to open the Command Menu. Start typing javascript , select Disable JavaScript, and then press Enter to run the command. JavaScript is now disabled.
I faced the same problem during development of the Don't track me Google User script / extension.
#Important note The
window
object in a Chrome contentscript cannot be accessed directly, in any way.
I have tested many methods, and the only reliable method is injecting the code through a dynamically created script tag. Have a look at this answer, or my extension's source code for more information.
I solved it by using Object.defineProperty
. With this method, you can define a property, and specify information about the getter, setter and property descriptors. In your case:
Object.defineProperty(window, 'foo', {
value: function(){/*This function cannot be overridden*/}
});
Or, if you want to capture the variable, and use it later:
(function() {
var originalFoo = function(){/*Default*/};
Object.defineProperty(window, 'foo', {
get: function(){
if (confirm('function logic')) return function(){/*dummy*/};
else return originalFoo;
},
set: function(fn){originalFoo = fn;}
});
})();
<script>
Object.defineProperty(window, 'foo', {value: function(){return 5;} });
</script><script>
function foo(){return 1};
alert(foo()); // Shows 5 in all browsers except for Chrome v17
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With