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

How to prevent iframe affecting browser history

本文关键字:历史 记录 浏览器 影响 何防止 iframe      更新时间:2023-09-26

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

我的页面中有一个iframe,我会使用Javascript更改其src值。整个事情运行良好,除了 src 的更改会影响浏览器历史记录。

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

我尝试过:

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

上面的两种方法都与直接在我的 Safari 浏览器上更改src没有什么不同。后退按钮仍会受到影响。

尚未在其他浏览器上测试过,但我认为其他 webkit 浏览器也是一样的。

我认为您的代码中还有其他我们没有看到的东西,因为.contentWindow.location.place在我的测试中起作用。

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

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

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

$( '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>