Window.postMessage() 解决父页面与iframe之间跨域通信问题,实时获取iframe消息动态
有个需求是:监听iframe窗体中,15分钟内未操作,界面弹出功能。
Window.postMessage()
MAN中有详解:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
targetWindow.postMessage(message, targetOrigin, [transfer]);
targetWindow:字向上传递消息时,可以用window.parent
targetOrigin:可写同源域名,也可写具体域名地址,也可用‘*’号;
1.首先建立页面index.html,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>父页面</title> </head> <body> <button onclick="handleEvent()">向子页面发送信息</button> <p>我是父页面</p> <iframe src="iframe.html" id="iframe"></iframe> <script> function handleEvent() { // iframe的id var f = document.getElementById('iframe'); // 触发子页面的监听事件 f.contentWindow.postMessage('close', '*'); } // 注册消息事件监听,接受子元素给的数据 window.addEventListener('message', (e) => { console.log(e.data); }, false); </script> </body> </html>
ps:如果是页面初始化就发送消息,需要iframe加载完成以后发送,
const t = document.getElementById('iframeS'); t.onload = function(){ t.contentWindow.postMessage('test1111','*'); }
2.建立iframe.html子页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>子页面</title> </head> <body> <button onclick="handleEvent()">向父页面发送信息</button> <p>我是子页面</p> <script> // 注册消息事件监听,接受父元素给的数据 window.addEventListener('message', (e) => { console.log(e.data); }, false); window.addEventListener('click', handleEvent, false); window.addEventListener('mousemove', handleEvent, false); window.addEventListener('keydown', handleEvent, false); window.addEventListener('mousedown', handleEvent, false); function handleEvent() { // 触发父页面的监听事件 window.parent.postMessage(+new Date(), '*'); } </script> </body> </html>
监听iframe界面操作,向上发送时间戳,更新动作。
这样就可以完美解决监听不到iframe窗体动作的问题了~~~