Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I overwrite an entire document with JavaScript

This is not a duplicate question for these reasons:

  • I am asking about how to replace the entire HTML document with JavaScript without jQuery or any other fancy extensions to JavaScript. Some of the other questions that are similar to this question deal with specific things like AJAX or jQuery.
  • I am NOT asking about why 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?

like image 786
Melab Avatar asked Oct 12 '25 01:10

Melab


1 Answers

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.

like image 185
K_AEI Avatar answered Oct 14 '25 17:10

K_AEI