Hi, I’m Dung Huynh Duc . Nice to meet you.

About Me

With over a decade of experience under my belt as a full-stack developer, I've had the opportunity to spearhead project teams at tech startups in Vietnam, Thailand, Japan and Singapore. Additionally, I have worked as a freelance engineer for various companies based in Asia Pacific, Europe, and North America.

Presently, I serve the role of a Senior Full Stack Software Engineer at ACX. I am consistently committed to exploring and acquiring knowledge on emerging and popular technologies.

react
iframe
website

Reload page from iframe with cross-domain support

Hi there,

This demo use React as a demonstration but it should work the same for other UI framework or with vanilla JS.

At first, we will send a message from the iframe to the parent.

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p>Reload Iframe Example</p>
        <p>
          <button
            type="button"
            onClick={() => {
              window.parent.postMessage("reload-page", "*");
            }}
          >
            Reload
          </button>
        </p>
      </header>
    </div>
  );
}

Then from a UI component, we will use useEffect to listen to messages from Iframe.

useEffect(() => {
    const listener = (event: any) => {
      // TODO: check origin source for security
      if (event.data === 'reload-page') {
        window.location.reload();
      }
    };

    // listen to reload message on iframe
    window.addEventListener('message', listener);

    return () => {
      // clean listener
      window.removeEventListener('message', listener);
    };
  }, []);

  return (
     <iframe
          title="Trading System"
          src={`https://reload-iframe-example.vercel.app`}
          sandbox="allow-same-origin allow-scripts"
        />
   );

That's all :) Cheer.