H5 课件有 iframe 的嵌套
1. 同步页面的 name 信息
将第一层的页面的 name 属性同步到 iframe 中
var iframeEl = document.querySelector('#test');iframeEl.contentWindow.name = window.name;
2. 信令中转
window.addEventListener('message', function (event) {if (!event.data) {return;}var module = event.data.module;var cmd = event.data.cmd;var data = event.data.data;if (module === 'TIW_H5WEB') {// 如果信令来自 iframe 页面,则将信令往白板传递if (event.origin === iframeEl.contentWindow.location.origin) {window.parent.postMessage(event.data, '*');} else {// 其他信令则往 iframe 传递iframeEl.contentWindow.postMessage(event.data, '*');}}});
3. 完整代码如下:
<!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><style>* {margin :0;padding: 0;}html, body {width: 100%;height: 100%;}iframe {width: 100%;height: 100%;}</style></head><body><iframe id="test" src="https://tic-res-1259648581.cos.ap-shanghai.myqcloud.com/board/h5webctrl/h5web.html" frameborder="0"></iframe><script>var iframeEl = document.querySelector('#test');iframeEl.contentWindow.name = window.name;window.addEventListener('message', function (event) {if (!event.data) {return;}var module = event.data.module;var cmd = event.data.cmd;var data = event.data.data;if (module === 'TIW_H5WEB') {// 如果信令来至 iframe 页面,则将信令往白板传递if (event.origin === iframeEl.contentWindow.location.origin) {window.parent.postMessage(event.data, '*');} else {// 其他信令则往 iframe 传递iframeEl.contentWindow.postMessage(event.data, '*');}}});</script></body></html>