javascript - 无法在反应组件中使用 postMessage
问题描述
我正在尝试打开一个弹出窗口并从反应组件传递一条消息,窗口打开(http://localhost:3001
)但未显示消息。下面是打开 popup 和 postMessage 到弹出窗口的代码:
React.useEffect(() => {
document.addEventListener("message", function(event) {
console.log('event data', event.data, event.source);
})
}, []);
const onAdd = () => {
const popup = window.open('http://localhost:3001/auth', 'authWindow','height=500,width=500');
popup.postMessage('data', 'http://localhost:3001');
}
在那个弹出窗口(http://localhost:3001/)打开我想向我的父窗口(http://localhost:3000/)传递一条消息,这是将消息传递给父级的代码:
const receiveMessage = (e) => {
console.log("message event", e.data);
e.source.postMessage("message: asasdas", 'http://localhost:3000')
// if (event.origin !== "http://localhost:3000")
// return;
}
React.useEffect(() => {
window.addEventListener("message", receiveMessage);
}, [])
但这也给出了一个错误:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:3001').
解决方案
使用BroadcastChannel API
. 我在我的项目中使用它并发现它更可靠。我没有看到你遇到的问题。
推荐阅读
- python - 确保线和置信带颜色相同,并且在 Matplotlib 中只有一个标签
- node.js - 带有 addToSet 的 Mongoose 重复键错误
- vue.js - 在 JS 中需要 Vue 组件
- javascript - 如何在(MongoDB)数据库中同时编辑笔记中的文本
- python - ValueError:无法将对象广播到单个形状,我正在尝试一次绘制带有 3 个条形的条形图,但出现此错误
- python - Python ijson - 嵌套解析
- html - 如何使可隐藏的 sidenav 具有正确的滚动条?
- c# - WPF DataGrid C# ObservableCollection.Insert() 中断 IsSelected
- c++ - 将一个类的数据存储在另一个类中
- genymotion - 打嗝套装无法捕获移动应用程序流量