如何“浏览器返回"使用pushState时? [英] How to "browser back" when using pushState?

查看:45
本文介绍了如何“浏览器返回"使用pushState时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

window.history.pushState(newUrl, "", newUrl);

我的问题是,如何确保在执行pushState时浏览器的后退按钮将正常运行,或者换句话说,应该后退?

My question is, how to make sure that when doing pushState the browser back button will function as normal or in other words should go "back"?

(不使用jQUery)

(without using jQUery)

推荐答案

后退"按钮的正常行为是浏览器返回上一个文档,但是当您使用 pushState 时,不是以前的文档.

The normal behaviour for the back button is for the browser to go back to the previous document, but when you use pushState, there isn't a previous document.

pushState 的重点是在更新URL时使浏览器保持在相同文档上.这伴随着JavaScript所应用的DOM更改.

The point of pushState is to keep the browser on the same document while updating the URL. This is accompanied by DOM changes applied with JavaScript.

这是转到新页面的模拟.

要使后退按钮看起来有效,您需要编写一个匹配的模拟,以转到上一页.

To make the back button appear to work, you need to write a matching simulation of going to the previous page.

您可以通过收听 a popstate 事件.

You can do this by listening for a popstate event.

Page <span id="p">1</span>

<button>Next</button>

<script>
document.querySelector("button").addEventListener("click", function () {
  document.getElementById('p').textContent++;
  history.pushState({}, "", "/" + document.getElementById('p').textContent);
});

addEventListener("popstate", function (e) {
  document.getElementById('p').textContent--;
  e.preventDefault();
});
</script>

这篇关于如何“浏览器返回"使用pushState时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆