TwilightSun
TwilightSun

Reputation: 2335

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:

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.

Upvotes: 21

Views: 14297

Answers (1)

tmdesigned
tmdesigned

Reputation: 2254

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>

Upvotes: 1

Related Questions