Getting cross Window messages by window.postMessage in NextJS wrong

1.1k Views Asked by At

I have need to communicate with a redirect page after a 3D secure Authorization is completed by Checkout Card payment provider. Because I don't want to change the Parent window location I have a setup like this

/payment.tsx

This is the page that opens a new window to 3DS Auth URL

export default function IndexPage() {
    useEffect(() => {
        //redirect will be replaced by 3d secure url
        // which after 3ds completes will redirect to /redirect
        const redirectWindow = window.open('/redirect')

        //I assume message posted by /redirect will be recieved here
        window.addEventListener('message', (event) => {
            //  if (typeof event.data === 'object' && 'key' in event.data) {
            if (typeof event.data === 'object' && 'key' in event.data && event.data.key === 'redirect') {
                console.log(event.data, 'Received From Redirect Window')
                redirectWindow?.close()
            }
        })
    }, [])

    return <div>Waiting for Redirect to send message</div>
}

The next page /redirect is where 3DS will return to after success or failure

import { useEffect } from 'react'

export default () => {
    useEffect(() => {
        window.addEventListener('message', (event) => {
            console.log(event)
            event.source?.postMessage({ key: 'redirect', message: 'Hi' }, '*')
            //}
        })
    }, [])
    return <div>Transaction Successfull I should be closed by my Parent Window</div>
}

The aim of this is to close the /redirect window by sending a message to /payment once Checkout 3DS completes and return to the application. This setup may not be a feasible approach so feedback is welcome. But at the moment I am unable to get any message sent from /redirect or thus unable to close the window.

Example code can be found in CodeSandbox

0

There are 0 best solutions below