3

我的计算机 (localhost) 上有一个 html 页面 ( test.html)。在我已abc.example.com加载的该页面上的 iframe 中。

我想abc.example.com从另一个域访问 iframe 的内容xyz.example.com。这是我迄今为止尝试过的:

//test.html in abc.example.com
<input type="textbox" />
<input type="submit" value="click_me" />

//Start.html in xyz.example.com

<script type="text/javascript">
  $(document).ready(function() {

    $("#ok").click(function() {
      //using javascript
      var oo = document.getElementById("myFrame");

      document.getElementById("divFrame").innerHTML = 
        oo.contentWindow.document.body.innerHTML;   
    });

  });
</script>

<iframe id="myFrame" src="http://localhost/exam/test.html"></iframe>
<div id="divFrame"></div>
<input type="submit" id="ok" />

但是当我按下“确定”按钮时,它会引发"Access is Denied"错误。在使用 jQuery 模拟 iframe 中的点击时,我也遇到了同样的错误:

var btn = window.frames[0].document.getElementsByName('click_me');
btn[0].click();
4

1 回答 1

4

In JavaScript you don't have access to frames on a different domain. It's called the Same origin Policy. If this was allowed you could, for instance, open a hidden frame to load facebook and google+ and steal everyone's info!

In some cases there is a way around the same origin policy but you need to explicitly whitelist a domain. Like when using Cross-origin resource sharing. So it is possible to dynamically (AJAX/XMLHTTPRequest) fetch data from another domain, but you must control the other domain as well.

于 2012-08-20T18:14:56.293 回答