iframe跨域访问

问题描述

子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()

在这里插入图片描述

解决方案

  1. 页面协议相同
  2. 端口号相同
  3. 主机相同,父子页面的Document.domain设为相同值




给iframe.html添加上domain之后就可以了
在这里插入图片描述

参考文献

  1. window.postMessage - Web API 接口参考 | MDN
  2. html5 postMessage解决跨域、跨窗口消息传递
发布了223 篇原创文章 · 获赞 63 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/lly1122334/article/details/104019156
今日推荐