node.js - Passing data from opened window
问题描述
I've been stuck on this problem for a day now and was wondering if there's a way I could go about this.
client side
Client side is going to be dynamic since it's an app type plugin.
The client side will open up a popup for oAuth purposes. Let's say its domain is www.google.com
I have the popup written like window.open('www.backend.com/api')
in ReactJS.
The client button is something like this:
<button onClick={() => iveBeenClicked()}> sync up </button>
and then it runs this function
const iveBeenClicked = (e) => {
e.preventDefault()
const popupWindow = window.open('www.backend.com/api', "_blank")
}
oAuth and backend with ExpressJS
This is the backend which we'll say is www.backend.com/api
router.use("/api", (req, res) => {
if (req.query.code) {
res.send(res.query.code)
} else {
res.redirect(
`www.ApiRouteThatRedirectsWhenComplete.com`
);
}
});
Well I have the code I want, but how can I send that to the client from a different domain? If there's an alternative to window.open()
where a user could press accept, please let me know.
So the big question is, how can client receive data from window.open's popup?
Thank you in advance!
#EDIT
So I finally got it thanks to @vishal-bartakke 's suggestion which I realized I implemented it wrong. I'm going to supply it here just in case it will help anyone that comes across this post.
for the ivebeenclicked() function in client side:
const iveBeenClicked = (e) => {
e.preventDefault()
const popupWindow = window.open('www.backend.com/api', "_blank")
//this is the part that was needed to receive the information of success
window.addEventListener('message', (e) => {
if (e.data) {
//do what you need to do with that key
}
})
}
in my expressjs's file:
router.use(['/api/', '/api/page?'], (req, res) => {
if (req.query.token) {
res.sendFile(path.join(__dirname +'/thatHTMLpage.html'))
} else {
res.redirect(`that route that does the oauth`)
}
})
In that html created upon success, I added this code to send in the data
window.onload = function () {
let urlParams = new URLSearchParams(window.location.search);
window.opener.postMessage(urlParams.get("code"), "*");
};
It is quite a messy setup but it works how I want it. Thanks!
解决方案
您可以使用 postMessage (在此处查看)在窗口之间进行通信。在子窗口中,您可以参考父窗口window.opener
来发布消息,在父窗口中您可以发布popupWindow
消息
推荐阅读
- python - 在 AWS lambda 函数中使用来自 S3 存储桶的 Pandas read_csv 时出错 - 第 5 行中预期有 1 个字段,看到 2
- java - 在验证中检查多个条件
- r - 如何将多个excel工作簿合并到数据框中使用R中新ID列中的特定单元格
- java - Micronaut:如何用@Context替换@EventListener与@Singleton结合?
- c++ - 如何在 vscode 中的 powershell 上运行命令?
- javascript - React,使用 useEffect 更新数据,一个数据是一个数组,但是当我使用 map 或 Object.keys(data).map 时,两者都不起作用。如何让它发挥作用?
- http - golang 正确的 http2 请求
- django - 如何在 Django 模型的 ManyToManyField 中添加 id(而不是对象)?
- c++ - 如何改进我的抽象可迭代构造以消除显式模板使用的需要?
- python - 如何在指定字符串的一部分之后抓取指定数量的字符?