有时候两个页面之间不是父子组件的情况下,信息交互很难搞,看到有人用postmessage来进行消息交互,我也试了一下,哎呀妈真香!!!
1、首先在需要发送消息的界面中使用postMessage
使用的是React+TypeScript,逻辑是更新提交的时候刷新打开当前页面的父窗口,postMessage用法如下:
1 2 3 4 5 6 7 8 | if (window.opener && window.opener.location && window.opener.location.href) {<!-- --> let origin = window.opener.location.href; let originStr = origin.substring(origin.length - 21, origin.length); if (origin.indexOf("/tankInfoManage/valve") != -1) {<!-- --> window.opener.postMessage("message", origin) } window.close(); } |
2、接收消息
1 2 3 4 | window.addEventListener('message', (e) => {<!-- --> ref.cuttent?.reload() ref.current?.clearSelected() }); |