> 文章列表 > 跨域 iframe 通信(页面引入跨域iframe)

跨域 iframe 通信(页面引入跨域iframe)

跨域 iframe 通信(页面引入跨域iframe)

场景

如果想要获取跨域iframe中的元素,由于浏览器的同源策略,直接获取是不允许的,形式如下

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title>
</head>
<body><div>容器</div><iframe id="iframe" src="跨域地址..."></iframe><script >const iframe = document.getElementById('iframe')console.log(iframe.contentDocument) // 由于iframe和这个页面不同域,获取不到该元素,并且会报错
</script>
</body>
</html>

解决

需要修改iframe工程中的代码,并且postMessage不能传递iframe中的dom对象

  1. 父容器通过postMessage向iframe发送消息,通知iframe
const iframe = document.getElementById('iframe')
iframe.contentWindow?.postMessage({ type: 'needcapture' }, '*'); //1.可以在{ type: 'needcapture' }中传递相关信息
  1. iframe内部,添加一个postMessage监听器,监听父窗口传递的message
  2. iframe内部,接收到父窗口的message后,把iframe中的信息传递给父窗口
window.addEventListener('message', (e) => {if (e.data && e.data.type === 'needcapture') { //2. 监听到父容器的消息window.parent.postMessage( // 3. 传递iframe中的相关信息{type: 'capture',// captureDom: captureDom,captureUrl: url,},'*');}
})
  1. 父容器也需要添加一个postMessage监听器,监听iframe传递的message
window.addEventListener('message', async (e) => {if (e.data && e.data.type === 'capture' && e.data.captureUrl) { //4. 监听到iframe的消息// 可以从e.data中获取相关消息,并执行相关操作}
})

其他

  • 当iframe传递Dom对象时,会出现报错:“DataCloneError:无法克隆对象。”

    • 退而求其次的解决:把需要对DOM对象的操作写在iframe中,只把执行结果通过postMessage传递给父容器
  • 如果使用的是不跨域的iframe,可以直接获取iframe中的DOM元素,不需要使用postMessage通信