Javascript 和同源 iframe [英] Javascript and same origin iframes

查看:17
本文介绍了Javascript 和同源 iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用页面上但在此框架之外的脚本读取/编辑 iframe 内容(不仅是 src 之类的属性)?我知道如果源来自其他站点是不可能的,因为这将是一个很大的安全漏洞,但我只问它是否适用于来自同一来源的其他内容.

Is it possible to read/edit iframe contents(not only properties like src) with scripts that are on page but outside of this frame? I know that is impossible if source is from other site as it would be a big serurity hole, but I only ask whether it works for other content from the same origin.

推荐答案

是的,如果 iframe 和父页面的位置在同一主机(同源策略),您可以执行此操作.

Yes, you can do this if the location of the iframe and parent page are of the same host (same origin policy).

为确保浏览器允许您执行此操作,您可以使用

To ensure the browser will let you do this, you can use

document.domain = "example.com" 

在父页面和 iframe 中.(注意 subdomain.example.com 和 example.com 是不同的)

on the parent page and in the iframe. (note that subdomain.example.com and example.com are different)

用于执行此操作的 Dom 方法(父页面到 iframe):

document.getElementById("myiframe").contentWindow.document.getElementById("divinframe").innerHTML = "I'm on the inside.";

document.getElementById("myiframe").contentWindow.someFunctionInsideIframe();

contentWindow 是答案,适用于大多数现代浏览器,当然还有 chrome、ie7+ 等.

contentWindow is the answer and works in most if not all modern browsers, certainly chrome, ie7+ etc.

另一种方式(iframe 到父页面):

top.document.getElementById("DivInTopParent")

这篇关于Javascript 和同源 iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆