如何防止iframe影响浏览器历史记录

Twi*_*Sun 12 html javascript

我在处理Web项目时遇到了浏览器历史记录问题.

我的页面中有一个iframe,我会src使用Javascript 更改其值.整个过程工作得很好,除了这个src的更改会影响浏览器历史记录.

当我更改iframe网址时,我不想推送浏览器历史记录.我希望用户离开整个基页并在单击后退按钮时转到上一个位置,而不是仅仅返回更改后的iframe.

我尝试过的:

  • 删除以前的iframe,并替换为具有新src值的新iframe
  • 使用replaceWith()jQuery的方法
  • 用于iframe.contentWindow.location.replace()替换iframe位置

上述两种方法都只是src在我的Safari浏览器上直接更改.后退按钮仍然受到影响.

还没有在其他浏览器上测试,但我认为其他webkit浏览器是相同的.

tmd*_*ned 1

我认为您的代码中还有其他我们没有看到的内容,因为 .contentWindow.location.replace 在我的测试中有效。

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

我还在 codePen 之外的空白 html 页面上进行了尝试,认为 codepen 编辑器正在影响结果。它继续工作。

我已将其作为代码片段粘贴在下面,尽管我认为这样不允许 iFrame 工作。

$( 'html' ).on( 'click', '.change-iframe', function() {
    $( '#dynamic-iframe' )[0].contentWindow.location.replace( $( this ).data( 'src' ) );
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)