问题描述
子iframe使用jQuery访问父页面时,报错Uncaught DOMException: Blocked a frame with origin "url" from accessing a cross-origin frame.
,这是跨域导致的
实例
设host
进行域名重定向,打开C:\Windows\System32\drivers\etc\HOSTS
添加一句
127.0.0.1 www.xercis.com
index.html
父页面设domain
<head>
</head>
<body>
<div style="background-color:orange; height:200px; width:50%; float:left;">
<input id="name" type="text" placeholder="输入姓名">
</div>
<div style="background-color:pink; height:200px; width:50%; float:right;">
<iframe src="iframe.html"></iframe>
</div>
<script>
document.domain = "xercis.com";
</script>
</body>
</html>
iframe.html
<head>
</head>
<body>
<button id="get">获取姓名</button>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
// document.domain = "xercis.com";
// 子iframe访问父页面元素
$("#get").click(function () {
alert($("#name", parent.document).val());
});
// 子iframe监听父页面元素
$("#name", parent.document).change(function () {
console.log($(this).val());
});
</script>
</body>
</html>
server.py
import sys
import tornado.web
import tornado.ioloop
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
app = tornado.web.Application([
(r"/", IndexHandler),
(r"/(.*)", tornado.web.StaticFileHandler, {"path": sys.path[0]}),
])
port = 8888
print("http://www.xercis.com:{}/".format(port))
app.listen(port)
tornado.ioloop.IOLoop.current().start()
解决方案
- 页面协议相同
- 端口号相同
- 主机相同,父子页面的Document.domain设为相同值
给iframe.html添加上domain之后就可以了