Detect URL change of SPA (single page app) inside iframe

Viewed 1077

I have a React web app which render iframe. The iframe shows simple website or SPA websites. I want to invoke a function every time the URL changes in the iframe. Multiple solutions are using the "onLoad" , but this doesn't work for SPA application URL changes as I checked. Anyone have a solution to detect iframe URL change of SPA?

Code example:

function App() {

  return (
    <div >
      <iframe id='iframeid' onLoad={(e)=>{console.log('page loaded', e)}} src="http://127.0.0.1:8001" style={{position: 'absolute', height: '100%', border: 'none'}} width='100%'></iframe>
    </div>

  );
}

export default App;

http://127.0.0.1:8001/ is SPA which I run locally

The onLoad work on the initial loading of the page, but when URL changes (using react-router) nothing happens.

1 Answers

If you have control over both the iframe and the wrapper you can use postMessage. Add an event handler inside your iframe so that when the document loads you post a message to the outer browser containing your new url.

Related