How to handle iframe contentDocument using prototype
If you want to use Prototype across different documents and iframes are different documents, you must include the script in each document and use the correct copy to access the linked document.
The same goes for jQuery and any other framework that links directly to document
. Each library instance is associated with its own object document
. So when you create an element from the parent script, its ownerDocument
the parent window. Try adding this element inside the iframe document and you should get DOMException.WRONG_DOCUMENT_ERR.
var iframe= $('myiframe');
// get window and document objects for iframe (IE compatible)
var idoc= iframe.contentDocument || iframe.contentWindow.document;
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;
Element.extend(idoc);
idoc.body.insert('<div>hello</div>'); // fail, wrong document
iwin.Element.extend(idoc); // use the copy of Prototype in the iframe window
idoc.body.insert('<div>hello</div>'); // ok
(Note that in Firefox you don't actually get WRONG_DOCUMENT_ERR because they intentionally capture this error silently for you, but more complex manipulations can quickly lead you to odd, inconsistent states.)
Most JS libraries are designed for easy one-document scripting; they hide most of the gory details involved in DOM manipulation, and one of the ways they do it is by returning an object document
. But that makes them less suitable for multi-document scenarios where knowing which to document
use is vital.
Scripts with multiple documents are already confusing. Using a JS framework that isn't specifically designed to handle it (and I don't know what it is) just makes life even weirder.
source to share