External JavaScript doesn't work in iFrames?

2019-08-23 05:55发布

问题:

I'm trying to create an iframe whose contentWindow.document is a document that I've created myself. I create the frame using:

var myFrame = document.createElement("iframe");

I create the document using:

var doc = document.implementation.createHTMLDocument("sampleTitle");

I use $.get()and a callback function to retrieve the innerHTML data of the page view I want to place in the iframe, then I place that data into the document by altering doc.body.innerHTML and doc.head.innerHTML. Finally, I fill the frame with the data in doc using:

var destDocument = frame.contentWindow.document;
var srcNode = doc.documentElement;
var newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);  

The problem: When I do this, external JavaScripts placed in the iframe's contentWindow.document don't work, even if the "src" attribute of the is the URL of an HTML file in the same folder as the parent document, and the "src" attribute in the contentWindow.document is the URL of a JavaScript file in the same folder.

However, JavaScripts work if I simply create an <iframe> and set the source to the URL of the page view I want. Why doesn't it work when I create the document myself? Is the stated location of the iframe in contentWindow.location.href different from the real location if I override the HTML pointed to by the "src" attribute?

回答1:

When you create an iframe and don't set a src attribute, its source is implicitly about:blank. This will prevent any relative links from working (because they're relative to about:blank!), and is also likely to cause a lot of Javascript to malfunction.

Unless you have a very good reason to do otherwise, you should set the source of the iframe to something on your domain to get its origin set up properly. Even just an empty HTML file is better than about:blank.