Skip to content

Instantly share code, notes, and snippets.

@sndrs
Created August 27, 2015 12:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sndrs/b27055580940da749ad5 to your computer and use it in GitHub Desktop.
Save sndrs/b27055580940da749ad5 to your computer and use it in GitHub Desktop.
Override document.write to prevent 3rd parties injecting blocking scripts
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
(function(Document) {
Document.prototype.write = function(s) {
var allScripts = document.getElementsByTagName('script'),
thisScript = allScripts[allScripts.length-1];
var writeTarget = document.createElement('div');
writeTarget.innerHTML = s;
window.onload = requestAnimationFrame(function () {
thisScript.parentElement.insertBefore(writeTarget, thisScript);
});
}
})(Document)
</script>
</head>
<body>
<div>div 1</div>
<script>
document.write("between 2 divs")
</script>
<div>div2</div>
</body>
</html>
@mxdvl
Copy link

mxdvl commented Sep 30, 2021

This is brilliant!

I’ve forked this for use with document.createElement in https://gist.github.com/mxdvl/bb4042dc1448745c3dc707dc771e0e1b

@topbestcoder
Copy link

A mistake :
})(Document) => })(document)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment