Change the URL of a parent window by using the pushState history when you click the link in Iframe

advertisements

I have a page that has a header and sidebar with a right content panel that is an Iframe.

In a page loaded into the right content panel, I am trying to have a clicked link update the Browser URL in the parent window to the URL of the new page that is loaded into the Iframe.

I do not want the actual parent window to reload the URL but simply to update the URL in the address bar.

Something like:

window.history.pushState('obj', 'newtitle', '/bookmarks/list/');

Is this possible from an Iframe?


Another solution using Window.postMessage().

Iframe:

<a href="/test">/test</a>
<a href="/test2">/test2</a>

<script>
Array.from(document.querySelectorAll('a')).forEach(el => {
  el.addEventListener('click', event => {
    event.preventDefault();
    window.parent.postMessage(this.href, '*');
  });
});
</script>

Main page:

Current URL: <div id="current-url"></div>
<iframe src="iframe-url"></iframe>

<script>
const $currentUrl = document.querySelector('#current-url');
$currentUrl.textContent = location.href;

window.addEventListener('message', event => {
  history.pushState(null, null, event.data);
  $currentUrl.textContent = event.data;
});
</script>

See demo on JS Fiddle.