【发布时间】:2013-05-07 13:52:25
【问题描述】:
我在 iframe 中加载了一个 html 文档。
我为该文档在 javascript 中开发了一些弹出菜单代码,并将代码从主文档注入到 iframe 中。
但我的代码在 iframe 中不起作用,因为它使用了“document”对象,而且令人惊讶的是,它指的是主文档而不是 iframe 文档。
我也玩内容选择,我需要window.getSelection(),它可以返回到主文档的选择,我需要window.frames[0].getSelection()。
我做错了吗?
有什么简单的方法可以解决这个问题吗?
更新:(澄清)
正如 Bergi 指出的那样,我的问题是关于如何正确运行注入的 javascript 代码以获取 iframe 中的本地范围而不是全局范围?
所以我确实不必须在代码中重写document 和window...
更新: (我的 html 的骨架)
<html>
<head></head> <!-- script launches on jquery's $(document).ready -->
<body>
<iframe>
[
<body>
...
<script></script> <!-- code injected here from the code (appended to the body) -->
</body>
]
</iframe>
</body>
</html>
脚本如下(使用 jquery):
$(function(){
$('iframe').load(function(){
var $doc = $('iframe').contents();
var $head = $('head', $doc);
$head.append('<link rel="stylesheet" href="/stylesheets/book-popup-menu.css" />');
var $body = $('body', $doc);
$body.append(' \
<div id="popup"> \
</div> \
');
$body.append(' \
<script type="text/javascript"> \
console.log(document.body);// it still displays the global body \
</script> \
');
});
});
【问题讨论】:
-
取决于您如何将代码注入 iframe - 请向我们展示 sn-p。如果你做错了,代码仍然在父文档的全局范围内执行。
-
@Bergi 谢谢,我已经按照你的要求更新了我的问题。
-
你说
/scripts/book-popup-menu.js是在document指向父框架的时候执行的? -
是的,完全正确。我做错了什么?
-
我还不知道发生了什么,但我可以确认问题。
标签: javascript jquery iframe