由于目前项目基础界面,业务逻辑一样,只是细微有所差别。因而使用iframe来进行定制化处理。
最初是想通过url
携带参数来进行区分,但是随着需求变多,定制化也越来越细微,若是再使用url进行处理,有些太累赘了。因而思量再三,开始使用postMessage
进行处理。
postMessage
message
可以传递对象targetOrigin
可以指定哪些窗口接收信息parent.html
<iframe id="iframe" src="http://DOMAIN1.com/child.html"></iframe>
const iframe = document.getElementByID('iframe')
const sendChildData = {
style: {
btn_color: '#fff'
}
}
// 默认只要是嵌套的页面都可以接收信息 *
iframe.contentWindow.postMessage(sendChildData, '*')
child.html
<button id="btn">提交</button>
window.addEventListener('message', function (e) {
if (!e.data) return
const { style } = e.data
const btn = document.getElementByID('btn')
btn.style.color = style.btn_color
}, false)
子向父传递参数
此处代码省略,简述实现原理
postMessage
, 哪儿接受message
iframe
窗口;同理子向父,就需要找到父窗口window.parent
message
直接使用 window.addEventListener(‘message‘, function () {}, false)
来进行处理即可window.onload
(因为onload是等所有资源加载才执行)postMessage
,因而最好相互沟通,或者传入特定参数进行判断,不然接收多次数据,就有些凌乱了setInterval
定时去查询,但是多少总有些不好。而使用postMessage
便可以简化,事件触发就调用一下发送postMessage
事件origin
,这样安全些iframe
多少总有些安全顾虑,最新Google
新出了一个标签Portals
,只是目前还没有正式开始原文:https://www.cnblogs.com/sinosaurus/p/11673153.html