Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent iframe affecting browser history

I'm encountering a browser history issue when working on a web project.

Theres an iframe in my page, which I would change its src value using Javascript. The whole thing works just fine except this change of src would affect the browser history.

I do not want to push the browser history, when I change the iframe url. I'm expecting that the user would leave the whole base page and go to the previous location when clicking on the back button, rather than just going back on the changed iframe.

What I've tried:

  • remove the former iframe, and replace with a new one having the new src value
  • use replaceWith() method from jQuery
  • use iframe.contentWindow.location.replace() to replace the iframe location

Both methods above behaved nothing different than just changing the src directly on my Safari browser. The back button is still affected.

Haven't tested yet on other browsers, but I assume other webkit browsers would be the same.

like image 552
TwilightSun Avatar asked Dec 07 '14 09:12

TwilightSun


People also ask

Does iframe work in all browsers?

The iframe element is supported by all modern desktop and mobile browsers.

Are iframe deprecated?

IFrames are not obsolete, but the reasons for using them are rare. Using IFrames to serve your own content creates a "wall" around accessing the content in that area. For crawlers like Google, It's not immediately clear that cotent in an iframe will be ranked as highly as if the content were simply part of the page.

Are IFrames dead?

Nope, iframes are definitely not dead.


1 Answers

I think there is something else in your code that we're not seeing, because .contentWindow.location.replace works in my testing.

https://codepen.io/tmdesigned/pen/WJEqON

I also tried that on a blank html page outside of codePen, thinking the codepen editor was affecting the outcome. It continued to work.

I've pasted it as a snippet below for the code, although I don't think SO allows iFrames to work.

$( 'html' ).on( 'click', '.change-iframe', function() {
    $( '#dynamic-iframe' )[0].contentWindow.location.replace( $( this ).data( 'src' ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="dynamic-iframe" width="560" height="315" src="https://www.youtube.com/embed/XlqoPpLMdwY" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> 

<div>
    <button class="change-iframe" data-src="https://www.youtube.com/embed/0RIrdFfy9t4">Another</button>
    <button class="change-iframe" data-src="https://www.youtube.com/embed/QMQbAoTLJX8">Another</button>
    <button class="change-iframe" data-src="https://www.youtube.com/embed/wppBd-52LT0">Another</button>
</div>
like image 87
tmdesigned Avatar answered Sep 18 '22 11:09

tmdesigned