Skip to content

Instantly share code, notes, and snippets.

@elbywan
Last active November 6, 2018 13:19
Show Gist options
  • Save elbywan/1aaef6abd33967b2b260c809bcc50384 to your computer and use it in GitHub Desktop.
Save elbywan/1aaef6abd33967b2b260c809bcc50384 to your computer and use it in GitHub Desktop.
const scriptElt //see above - result of the monkey patched createElement
// Backup the original setAttribute function
const originalSetAttribute = scriptElt.setAttribute.bind(scriptElt)
// Define getters / setters to ensure that the script type is properly set
Object.defineProperties(scriptElt, {
'src': {
get() {
return scriptElt.getAttribute('src')
},
set(value) {
if(needsToBeBlacklisted(value, scriptElt.type)) {
originalSetAttribute('type', 'javascript/blocked')
}
originalSetAttribute('src', value)
return true
}
},
'type': {
set(value) {
const typeValue =
needsToBeBlacklisted(scriptElt.src, scriptElt.type) ?
'javascript/blocked' :
value
originalSetAttribute('type', typeValue)
return true
}
}
})
// Monkey patch the setAttribute function so that the setter is called instead.
// Otherwise, setAttribute('type', 'whatever') will bypass our custom descriptors!
scriptElt.setAttribute = function(name, value) {
if(name === 'type' || name === 'src')
scriptElt[name] = value
else
HTMLScriptElement.protytope.setAttribute.call(scriptElt, name, value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment