【问题标题】:Access iframe content on same domain访问同一域上的 iframe 内容
【发布时间】:2012-10-31 15:07:57
【问题描述】:

我正在尝试创建一个简单的测试来从其父容器修改 iframe 的内容,并从 iframe 修改父容器的内容。到目前为止,这是我所拥有的:

first.html:

<!doctype html>
<html>
  <head>
    <title>First</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="shared.js"></script>
    <script type="text/javascript" src="first.js"></script>
  </head>
  <body>
    <h1>First</h1>
    <iframe src="http://localhost:3000/second.html"></iframe>
  </body>
</html>

second.html:

<!doctype html>
<html>
  <head>
    <title>Second</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="shared.js"></script>
    <script type="text/javascript" src="second.js"></script>
  </head>
  <body>
    <h1>Second</h1>
  </body>
</html>

shared.js:

function modifyContent(targetContainerElement, targetSelector, sourceString) {
  $(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}

first.js:

$(document).ready(function() {

  var iframe = $("iframe");
  modifyContent(iframe.contents(), "h1", "First");
});

second.js:

$(document).ready(function() {

  if (!top.document)
    return;

  modifyContent(top.document.body, "h1", "Second");
});

要运行代码,我使用python -m SimpleHTTPServer 3000 并导航到localhost:3000/first.html。第一个标题被修改并显示“第二个修改!”但第二个标题只是说“第二”。我在这里错过了什么?

【问题讨论】:

    标签: javascript iframe cross-domain


    【解决方案1】:

    在 iframe 完全加载后尝试更改 iframe 内的 h1 标签:

    $(document).ready(function() {
    
      var iframe = $("iframe");
      iframe.load(function ()
      {
        modifyContent(iframe.contents(), "h1", "First");
      });
    });
    

    另外我认为你应该重写modifyContent

    function modifyContent(isJquery, targetContainerElement, targetSelector, sourceString) 
    {
      if ( isJquery )
        targetContainerElement.find(targetSelector).html("Modified by " + sourceString + "!");
      else
        $(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
    }
    

    只需targetContainerElement 就可以了,因为您实际上不需要将它包装在 $() 中,因为它已经是一个 jquery 对象

    【讨论】:

    • 不是 second.js 中的 jQuery 对象。
    • 为这两种情况重写了我的代码。如果元素是 jQuery 对象,只需传递附加参数 isJquery
    • 页面和 iframe 是否来自同一个域?
    • 是的。一切都在问题之中。事实上,它在标题中。
    • 如果你只是从主页运行 $("iframe").contents().find('h1').html('test') 会发生什么?
    猜你喜欢
    • 2014-08-02
    • 2014-03-16
    • 1970-01-01
    • 2015-10-01
    • 2013-08-02
    • 2016-05-03
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多