我怎么能得到注入javascript代码在iframe的局部范围内执行

How can I get injected javascript code executed in local scope in iframe?

本文关键字:iframe 局部 范围内 执行 代码 怎么能 注入 javascript      更新时间:2023-09-26

我在iframe中加载了一个html文档。
我已经为该文档开发了一些javascript弹出菜单代码,并将代码从主文档注入iframe。

但是我的代码不能在iframe中工作,因为它使用"document"对象,并且令人惊讶的是指主文档而不是iframe文档。

我也玩内容选择,我需要window.getSelection()回到主文档的选择,我需要window.frames[0].getSelection()代替。

我做错了什么吗?
有没有什么简单的解决办法?

更新:(澄清)
正如Bergi指出的那样,我的问题是如何正确运行注入的javascript代码以获得iframe中的局部作用域而不是全局作用域?
所以我做必须重写document 's和window 's的代码…

更新:(my 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> '
');
});
});

UPDATE: A fiddle demonstration the issue

我终于找到了答案!

如果你用jQuery添加代码,比如$body.append('<script>'),那么"元素将由document.createElement('script')创建,因此将成为全局文档的一部分。即使在插入iframe文档之后,它将在全局命名空间中执行。

所以解决方案是——利用这个神话般的解决方案:(向Iframe注入Javascript)——回到香草Javascript:

$('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>');// non-javascript content works fine
    var doc = $('iframe').contents()[0]; // doc = $doc[0] does not work for some reason... 
    var script = doc.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.textContent = "console.log(document.body)"; // this will be iframe's body
    $body[0].appendChild(script1); // $body.append(...) does not work
});