Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you replace the document in a window?

var newDoc = document.implementation.createHTMLDocument('someTitle');
// swap newDoc with document

DOMImplementation.createHTMLDocument

  • Is it possible to swap the current document for a new document?
  • Is there any reasonable reason to do this?
like image 918
Raynos Avatar asked Dec 31 '11 17:12

Raynos


2 Answers

You cannot replace the current document object or any document object with the Document object created with createHTMLDocument method.

The createHTMLDocument was first introduced in one of the drafts of the DOM Level 2 Core, but was later removed from the final recommendation.

It was later added to the HTML5 spec as there was no programmatic way to create an HTML document.

Some of the use cases provided for programmatic creation of an HTML document were,

  • Create a non-rendered HTML document to upload via XMLHttpRequest (instead of sending an XML document).

  • Feature-test the HTML DOM in library code in a way that is guaranteed to avoid side effects on the displayed document.

  • Create an isolated non-rendered document from a rich text editing area, so client-side cleanup can be done before uploading without disturbing the live DOM that the user may still edit further.

  • Implement HTML5 parsing algorithm client-side in JavaScript for testing and comparison purposes, or for virtualization or object-capability-based security.

    An invisible iframe can be used for most of these purposes but that is more expensive in terms of resources. W3C mailing list

The conversation on W3C mailing lists that brought the method back into the spec, [Bug 7842] New: No programmatic way to make an HTML document - consider adding createHTMLDocument

like image 147
Livingston Samuel Avatar answered Nov 13 '22 08:11

Livingston Samuel


There is stuff in the document that is not really related to the DOM tree it contains, such as document.cookie, location and URL. It's much safer if we cannot replace global objects like window and document.

But what you are looking for can be effectively achieved by replacing the main document's documentElement with the other document's documentElement. It will have exactly the same effect that you are looking for.*

document.replaceChild(
    document.importNode(newdoc.documentElement, true),
    document.documentElement
);

As for reasons to do it, I have so far found one that cannot be achieved with an iframe.

* Note that if the doctypes are different, you'd have to replace the main document's doctype node with the other document's doctype node separately.

like image 34
Esailija Avatar answered Nov 13 '22 08:11

Esailija