Our app is written in React so your use case may differ syntactically, but the idea is the same. First up, let's assume you have an existing and working Cookie popup ready. When a user clicks on I accept to accept the cookies, fire the postMessage to the parent element:

window.parent.postMessage(
	{
		msg: 'message-content',
	},
	'*',
);

This exposes the message to the eventual containers your site is loaded with iframe into.

Note the * wildcard which allows any domain to read this message. Change this to the URL of the site you're embedding the site into to allow only that URL.

Next up, in the parent site, you should load the following snippet:

window.addEventListener(
  "message",
  function (e) {
    if (e.data.msg === "message-content") {
      document.cookie = "your_cookie_name=true";

      // Make sure to reference the ID given to the iframe element here.
      const iframeEl = window.document.getElementById("iframe-id");
      iframeEl.contentWindow.postMessage(
        { 
        	msg: 'message-content',
        },
        '*',
      );
    }
  },
  false
);

This snippet adds an event listener that keeps track of the message event. Also, note the wildcard operator (*) which should be replaced with the target origin to control which parent sites you send the message to. Once a message event is fired, we check if it's the same one as we've sent:

if (e.data.msg === 'message-content') 

If the condition above resolves to true, set your cookies in the parent site.

Once the cookies are successfully set in the parent site, repeat the previous step, but the other way around. Send the message using postMessage method on the  iframe element which you get by assigning a unique ID to the element itself.

Back in our app that's now rendering inside an iframe, listen for the message event. Message event here tells us that the cookie has been successfully set in the parent site. When the message is received, fire up your actions to close the popup.

window.addEventListener('message', () => {
	closeCookiePopup();
});

After this, you're done! It's three fairly simple steps that are unnecessarily complicated explanations on the internet.

There are a couple of things to keep in mind:

  • If you're testing this using a plain old HTML document to create an iframe, document.cookie won't work, at least with Chrome. Setting cookies in a local environment doesn't work for some reason.
  • Use serve package from NPM for testing the site(s) on a local machine (https://www.npmjs.com/package/serve).
  • Make sure to update the * (wildcard) to the specific URL you're transmitting the message to.

Thank you for taking the time to read this post, and feel free to share your thoughts and drop us an email at hello@prototyp.digital. 😄