Reload page from iframe with cross-domain support

Sep 10, 2021 · Dung Huynh

Context

When an iframe is cross-domain, direct parent access is blocked. Use postMessage API with a message listener to communicate between iframe and parent.

Usage

Inside iframe (sender):

<button onClick={() => window.parent.postMessage("reload-page", "*")}>
  Reload Parent
</button>

In parent page (receiver):

useEffect(() => {
  const listener = (event: MessageEvent) => {
    // TODO: Verify event.origin for security
    if (event.data === "reload-page") {
      window.location.reload();
    }
  };

  window.addEventListener("message", listener);
  return () => window.removeEventListener("message", listener);
}, []);
<iframe
  src="https://your-iframe-url.com"
  sandbox="allow-same-origin allow-scripts"
/>

Security: Replace "*" with specific origin in production.