JavaScript跳转页面,没有历史记录-location.replace()方法和history.replaceState()方法

location.replace()

用新的文档替换当前文档,相当于 跳转页面,但浏览器 不可以 后退,清空历史记录了

例子

创建 1.html,内容如下:

  1. <button onclick="jump()">跳转</button>
  2. <script>
  3. function jump(){
  4. location.replace('result.html')
  5. }
  6. </script>

创建 result.html ,内容如下:

  1. 结果页面

1.html 中,点击按钮,跳转到 result.html

关键:浏览器历史记录中,没有 1.html

history.replaceState()

HTML5为history对象添加 history.replaceState() 方法,把当前的页面的历史记录替换掉

  1. history.replaceState(state, title, url);

参数解释:

  • state: object类型,状态对象,一般为 null。是一个由 pushState() 方法创建的、与历史纪录相关的javascript对象。当用户定向到一个新的状态时,会触发popstate事件。事件的state属性包含了历史纪录的state对象。

  • title:新页面的标题,但是 所有浏览器目前都忽略这个值,因此这里可以填 null

  • URL:新历史纪录的url。新URL必须和当前URL在 同一个域,否则,pushState() 将抛出异常。这个参数可选,如果它没有被特别标注,会被设置为文档的当前URL

例子

创建 1.html,内容如下:

  1. <button onclick="jump()">跳转</button>
  2. <script>
  3. function jump(){
  4. history.replaceState(null,null,'5.result.html')
  5. }
  6. </script>

创建 result.html ,内容如下:

  1. 结果页面

1.html 中,点击按钮,跳转到 result.html

关键:浏览器历史记录中,没有 1.html


原文出处:http://malaoshi.top/show_1GWUFbiKpET.html