问题
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>