javascriptgoogle-chromecookiesgoogle-chrome-app

In chrome website rendering in iframe with different domain is unable to set and get cookies


Website a.com is rendering b.com in iframe. When running website b.com alone, everything is working fine. But when running a.com, website b.com is unable to set or get cookies.

Cookies.set(Key,Value,{sameSite:'None',secure:true,expires:30,domain:'b.com'})


Solution

  • Iframe child cookies cannot be set in parent and vice versa. It is restricted due to security reason. The best possible way is using postmessage from parent widow.getElementById("iframeId").contentWindow.postMessage("your message","*");

    Child listen to that message

        const allowedOrigins = new Set();
        allowedOrigins.add('localhost:3000');
        await window.addEventListener("message", (event) => {
        if(event.origin) {
        const originUrl = new URL(event.origin);
        const originHost = originUrl.host;
        if(!allowedOrigins.has(originHost)) {
            return;
        } else {
            //do your thing
          }
        }```