I have a server using passport for authentication, I would like to open the auth window in a external screen from my React app and know when the auth was successful, I tried something like below
const Home = () => {
const externalWindow = useRef<Window | null>()
useEffect(() => {
window.addEventListener("message", receiveMessage, false)
return () => {
window.removeEventListener("message", receiveMessage)
}
}, [])
const receiveMessage = async (event: MessageEvent<boolean>) => {
// if (event.origin !== "http://localhost:3000") {
// return
// }
if (event.data === true) {
console.log(event.data)
}
}
const handleClick = () => {
if (!externalWindow.current || externalWindow.current.closed) {
const width = 600
const height = 700
const top = window.screenY + (window.outerHeight - height) / 2.5
const left = window.screenX + (window.outerWidth - width) / 2
externalWindow.current = window.open(
"http://localhost:4000/auth/google",
undefined,
`toolbar=no, menubar=no, width=${width}, height=${height}, top=${top}, left=${left}`
)
}
}
fastify.get(
"/auth/google",
{
preValidation: fastifyPassport.authenticate("google", {
scope: ["profile", "email"],
}),
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
async () => {}
)
fastify.get(
"/auth/google/callback",
{
preValidation: fastifyPassport.authenticate("google"),
},
async (_request, reply) => {
return reply.header("Content-Type", "text/html").send(`
<script>
if (window.opener) {
window.opener.focus()
window.opener.postMessage(true)
}
window.close()
</script>
`)
}
)
However I never seem to receive the true value in React, I am not sure if there is a nicer way to achieve this
question from:
https://stackoverflow.com/questions/65869477/how-to-send-a-message-from-a-external-window-to-a-react-app 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…