If you want to re-enable script tags later on, my solution was to break the browser environment so that any script that runs will throw an error fairly early. However, it's not totally reliable, so you can't use it as a security feature.
If you try to access global properties Chrome will throw an exception.
setTimeout("Math.random()")
// => VM116:25 Uncaught Error: JavaScript Execution Inhibited
I'm overwriting all overwritable properties on window
, but you could also expand it to break other functionality.
window.allowJSExecution = inhibitJavaScriptExecution();
function inhibitJavaScriptExecution(){
var windowProperties = {};
var Object = window.Object
var console = window.console
var Error = window.Error
function getPropertyDescriptor(object, propertyName){
var descriptor = Object.getOwnPropertyDescriptor(object, propertyName);
if (!descriptor) {
return getPropertyDescriptor(Object.getPrototypeOf(object), propertyName);
}
return descriptor;
}
for (var propName in window){
try {
windowProperties[propName] = getPropertyDescriptor(window, propName)
Object.defineProperty(window, propName, {
get: function(){
throw Error("JavaScript Execution Inhibited")
},
set: function(){
throw Error("JavaScript Execution Inhibited")
},
configurable: true
})
} catch (err) {}
}
return function allowJSExecution(){
for (var propName in window){
if (!(propName in windowProperties)) {
delete windowProperties[propName]
}
}
for (var propName in windowProperties){
try {
Object.defineProperty(window, propName, windowProperties[propName])
} catch (err) {}
}
}
}
script-src:"self"
you allow only scripts from your domain to run in the page. If you are interested, read this article from Mike West about CSP.</div>
to close this DOM element and then starting a new<div>
that will be a sibling of the one where scripts aren't running?