解决跨域Uncaught DOMException: Blocked a frame with origin ** from accessing a cross-origin frame问题

本文介绍了在iframe中遇到的跨源通信限制,即Uncaught DOMException: Blocked a frame with origin。提出了解决方案,利用HTML5的window.postMessage方法进行安全的跨源通信。通过示例展示了如何在父页面和iframe窗口之间双向发送消息,确保了不同源之间的数据传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

iframe窗口修改元素,提示Uncaught DOMException: Blocked a frame with origin ** from accessing a cross-origin frame,无法修改

在这里插入图片描述

解决办法:

使用 postMessage() 方法用于安全地实现跨源通信

window.postMessage(message,targetOrigin) 方法是html5新引进的特性,可以使用它来向其它的window对象发送消息,无论这个window对象是属于同源或不同源,目前IE8+、FireFox、Chrome、Opera等浏览器都已经支持window.postMessage方法

语法
otherWindow.postMessage(message, targetOrigin, [transfer]);

参数 说明
otherWindow 其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
message 将要发送到其他 window的数据。
targetOrigin 指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI。
transfer 可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

postMessage双向发送消息

父页面

<div style="margin-bottom: 20px;">
    <button onclick="handleEvent()">向子页面发送信息</button>
</div>
<iframe src="iframe.html" id="iframe"></iframe>
<script>
    function handleEvent() {
        // iframe的id
        var f = document.getElementById('iframe');
        // 触发子页面的监听事件
        f.contentWindow.postMessage('父页面发的消息', '*');
    }

    // 注册消息事件监听,接受子元素给的数据
    window.addEventListener('message', (e) => {
        console.log(e.data);
    }, false);
</script>

iframe窗口

<button onclick="handleEvent()">向父页面发送信息</button>
<p>子页面</p>
<script>
    // 注册消息事件监听,接受父元素给的数据
    window.addEventListener('message', (e) => {
        console.log('iframe=' + e.data);
    }, false);

    function handleEvent() {
        // 向父页面发消息
        window.parent.postMessage('子页面发的消息', '*');
    }

</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值