访问同一域中的iframe内容

时间:2012-11-12 07:05:00

标签: javascript iframe cross-domain

我正在尝试创建一个简单的测试,以便从其父容器修改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。第一个标题被修改并说“由Second修改!”但第二个标题只是说“第二个”。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

尝试在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对象了