This is not a duplicate question for these reasons:
document.write()
only appends to the page. Perhaps the pure JavaScript solution I am looking for may incorporate that function, but it cannot only be that since it is inadequate by itself.What I am looking to do is overwrite a webpage as it is displayed in the browser with only HTML. The function document.write()
only appends whatever argument is passed to it to the document's body. The property document.documentElement.outerHTML
can be read from, but unlike when it is used on a page's child elements, cannot be written to, and even if it could, it would leave the DOCTYPE untouched.
I am working on a bookmarklet, so this JavaScript would not run in the page, meaning there is no problem with the script being overwritten while it is running. It could also be run in the browser's developer tools.
As an example, suppose I have about:blank
opened in my browser. The contents of the DOM would look like this:
<html>
<head></head>
<body></body>
</html>
I want to be able to overwrite it with whatever string I want. So, for instance, I could make it look like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example</title>
</head>
<body>
<p>This is an example.</p>
</body>
</html>
How can I achieve that sort of overwrite of a document?
Try this:
function one() {
document.write('<html><body><pre>the first html</pre></body></html>');
document.close(); // this makes the difference
}
function two() {
document.write('<html><body><pre>the second html</pre></body></html>');
document.close();
}
Refer to linstantnoodles' answer in question document.write() overwriting the document?
, the document.open
is implicitly called before the document.write
is called, but the document.close
doesn't, and
document.write()
when document is closed = rewrite the document;
document.write()
when document is open = append to the document.
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