外部JavaScript在iFrame中不起作用? [英] External JavaScript doesn't work in iFrames?

查看:135
本文介绍了外部JavaScript在iFrame中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个iframe,该iframe的contentWindow.document是我自己创建的文档.我使用以下方法创建框架:

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");

我使用$.get()和一个回调函数来检索要放置在iframe中的页面视图的innerHTML数据,然后通过更改doc.body.innerHTMLdoc.head.innerHTML将该数据放入文档中.最后,我使用doc中的数据填充框架:

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);  

问题:执行此操作时,即使iframe的"src"属性是与父文档位于同一文件夹中的HTML文件的URL,放置在iframe的contentWindow.document中的外部JavaScript也无法正常工作, contentWindow.document中的"src"属性是同一文件夹中JavaScript文件的URL.

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.

但是,如果我只是创建一个<iframe>并将源设置为所需的页面视图的URL,JavaScript就会起作用.为什么我自己创建文档时不起作用?如果我覆盖"src"属性指向的HTML,则iframe在contentWindow.location.href中声明的位置是否与实际位置不同?

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?

推荐答案

创建iframe且未设置src属性时,其源隐式为about:blank.这将阻止任何相对链接正常工作(因为它们相对于about:blank!),并且还可能导致许多Javascript出现故障.

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.

除非您有充分的理由这样做,否则应将iframe的来源设置为您域中的 something ,以正确设置其来源.甚至只是一个空的HTML文件都比about:blank好.

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.

这篇关于外部JavaScript在iFrame中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆