Monday, 8 April 2019

Async/Await answer onMessage event in cross-domain communication with an iframe

I have an iframe, which is communicating with its parent window to set and get some essential cookies via postMessage method.

At first a function in the iframe application requests Cookie A from the parent window.

    function requestCommunication(topic, customerId) {

            function cookieAvailable() {
                return new Promise(function(resolve) {
                    resolve(thisChatClient.cookie.getCookieData('sess_au'));
                });
            }

            console.log(cookieAvailable());

            if(!!cookieAvailable()) {
                //doStuff        
            }
     }

cookieAvailable() triggers the message from the iframe to the parent.window. In turn, the window returns the cookie with its data as string. This gets done by using the following:

 async function getCookieData(cookieName) {

        const allowedOrigins = [
           'https://domain.de',
        ];   

        const {data} = await new Promise(resolve => {

            window.onmessage = (event) => {
                this.allowedOrigins = allowedOrigins;

                this.isAllowedOrigin = (origin) => {
                    return this.allowedOrigins.includes(origin);
                }

                if (!this.isAllowedOrigin(event.origin)) {
                    return;
                }

                resolve(event);
                var returnedMessage = JSON.parse(event.data);
                return returnedMessage;
            }
        });

        var cookieContent = JSON.parse(data);
        var cookieContentData = JSON.parse(cookieContent.data);

        return cookieContentData; //this returns the cookie data (in almost all cases)
    }    

I don't get how to use the promise correctly to hand it over to my initial trigger function. I would appreciate any support.



from Async/Await answer onMessage event in cross-domain communication with an iframe

No comments:

Post a Comment