我在处理 Web 项目时遇到浏览器历史记录问题。
我的页面中有一个 iframe,我会使用 Javascript 更改它的 src
值。
除了 src 的这种更改会影响浏览器历史记录之外,整个事情都很好。
我不想在更改 iframe url 时推送浏览器历史记录。 我希望用户在单击后退按钮时离开整个基页并转到之前的位置,而不是仅仅返回到已更改的 iframe。
我尝试过的:
- 删除以前的 iframe,并替换为具有新
src
值的新 iframe - 使用 jQuery 中的
replaceWith()
方法 - 使用
iframe.contentWindow.location.replace()
替换 iframe 位置
上述两种方法的行为与直接在我的 Safari 浏览器上更改 src
没有什么不同。后退按钮仍然受到影响。
还没有在其他浏览器上测试过,但我假设其他 webkit 浏览器也是一样的。
最佳答案
我认为您的代码中还有我们没有看到的其他内容,因为 .contentWindow.location.replace 在我的测试中有效。
https://codepen.io/tmdesigned/pen/WJEqON
我还在 codePen 之外的空白 html 页面上尝试过,认为 codepen 编辑器会影响结果。它继续工作。
我已将它粘贴为下面的代码片段,但我认为 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>
关于javascript - 如何防止iframe影响浏览器历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27341498/