如何在 JavaScript 中使用 window.history?

How do I use window.history in JavaScript?

我在 Stack Overflow 上发现了很多关于此的问题,但它们都对某些部分非常具体。我确实找到了 this 个问题,其答案提供了一些很好的参考,但他们实际上并没有解释它是如何工作的,而且他们的例子几乎没有做任何事情。我想更多地了解它们是如何协同工作的,我想使用 vanilla JavaScript.

(此外,其他问题的许多答案都是多年以前的了。)

开始使用

首先,您可以删除window部分。只需 history 即可。但在我们了解一切如何协同工作之前,我们需要知道我们可以使用什么。

重要事件

window.onload

只要加载您的网页,就会触发此事件。有两种情况会触发此事件:

  1. 当您的网页从另一个网页导航到时。注意我写的是webpage,不是website。在同一站点的页面之间移动将触发此事件。
  2. 您的网页刚刚刷新。

window.onpopstate

当您在 设置的历史状态之间导航时,将触发此事件。您的浏览器会在正常浏览期间自动设置历史记录状态(为空),但浏览 to/from 这些状态不会触发此事件。

window.onunload

只要您的网页被卸载,就会触发此事件。有两种情况会触发此事件:

  1. 当您从您的网页导航到另一个网页时。
  2. 就在您的网页刷新之前。

重要Objects

历史界面包含五个函数(如下所述),两个 read-only object(此处描述),工作方式有点像 linked list。历史object的每个'link'中包含的两个object是:

  • length - 这是当前浏览器的历史状态数 window。它从 1 开始。
  • state - 这是一个 JavaScript object 几乎可以包含任何东西。默认为null

您可以分别调用history.lengthhistory.state来访问它们,尽管history.state只能用于获取当前历史状态.

重要功能

history.go(距离)

此功能与在浏览器中按后退或前进按钮的功能相同,但增加了能够准确指定您想走多远的功能。例如,history.go(3) 与按三下前进按钮的效果相同,但实际上不会加载开始和结束位置之间的页面。负值同样会使您在历史记录中倒退。 history.go(0)history.go(),甚至history.go(NaN)与刷新页面效果一样(这不会触发popstate事件)。如果您不能将 forward/backward 移动到指定的距离,该函数将不执行任何操作。

history.back()

此功能与浏览器中的后退按钮功能相同。它相当于 history.go(-1)。如果不能返回,该函数将不执行任何操作。

history.forward()

此功能与浏览器中的前进按钮功能相同。它相当于 history.go(1)。如果无法继续,该函数将不执行任何操作。

history.replaceState(州, 标题[ 地点])

这个函数取代了当前的历史状态。它需要三个参数,但最后一个参数是可选的。参数是:

  • state - 这是最重要的论点。您为此参数提供的 object 将保存到 history.state 以供以后检索。这是一个深拷贝,所以如果你以后修改原来的 object 它不会改变保存的状态。您也可以将其设置为 null,但如果您不打算使用它,那么使用 history 根本没有多大意义。
  • title - HTML 标准建议浏览器可以在用户界面中使用传递给此参数的字符串,但目前没有浏览器对其执行任何操作。
  • location - 此参数允许您更改相对于当前页面的 URL。它不能用于将 URL 更改为另一个网站的 URL,但可以用于将 URL 更改为 您的 网站上另一个页面的 URL。但是,我建议不要这样做,因为即使 URL 属于另一个页面,该页面实际上并没有重新加载。使用 back/forward 将显示更改后的 URL,但不会更改页面,并且会触发 popstate 而不是 loadunload。更改 URL 后刷新页面将加载 URL 指定的页面,而不是您之前所在的页面。此功能可用于为您的页面提供当前状态的 link,但我建议只更改查询字符串而不是完整的 URL。如果不使用此参数,则 URL 不会更改。

history.pushState(州, 标题[ 地点])

此函数与 history.replaceState 的工作方式相同,只是它将新状态 放在当前状态 之后,而不是替换当前状态。以前可以使用 forward 访问的所有历史状态都将被丢弃,新状态成为当前状态。

组装零件

历史界面对于允许您的用户通过动态导航非常有用从他们的浏览器中生成内容而无需重新加载整个页面,但您需要注意用户可能执行的所有可能影响历史状态的操作。

  1. 第一次导航到您的页面
    • 您的用户应该收到 menu/list 一些特定的动态生成内容,还是一些随机动态生成的内容?
    • 如果没有 history,甚至 JavaScript,您的页面会正确显示吗?
  2. 使用 back/forward 到 return 到您的页面
    • 您的用户应该看到他们第一次看到的相同内容,还是应该看到内容中反映的访问结果? ("Welcome Back" 消息对某些人来说可能是一种很好的接触,但对其他人来说却是不必要的干扰。)
  3. 正在刷新您的页面
    • 您应该获取新页面,return 到起始页面,还是重新加载同一页面? (如果 URL 没有改变,您的用户可能不会期待最后一个。)
  4. 使用刷新页面中的 back/forward
    • 你应该获取与刷新页面相关的新内容,还是重新加载之前保存的状态?
  5. 离开您的页面
    • 离开前需要保存什么吗?
  6. 通过 deep link 返回您的页面
    • 您是否有适当的代码来识别和处理深度 link?

请注意,无法删除已保存的状态(除了上面提到的 pushState() 的特定情况)。只能用新内容替换。

把它们放在一起

因为这开始有点罗嗦,让我们用一些代码来结束它。

// This function is called when the page is first loaded, when the page is refreshed,
// and when returning to the page from another page using back/forward.
// Navigating to a different page with history.pushState and then going back
// will not trigger this event as the page is not actually reloaded.
window.onload = function() {
  // You can distinguish a page load from a reload by checking performance.navigation.type.
  if (window.performance && window.PerformanceNavigation) {
    let type = performance.navigation.type;
    if (type == PerformanceNavigation.TYPE_NAVIGATE) {
      // The page was loaded.
    } else if (type == PerformanceNavigation.TYPE_RELOAD) {
      // The page was reloaded.
    } else if (type == PerformanceNavigation.TYPE_BACK_FORWARD) {
      // The page was navigated to by going back or forward,
      // though *not* from a history state you have set.
    }
  }

  // Remember that the browser automatically sets the state to null on the
  // first visit, so if you check for this and find it to be null, you know
  // that the user hasn't been here yet.
  if (history.state == null) {
    // Do stuff on first load.
  } else {
    // Do stuff on refresh or on returning to this page from another page
    // using back/forward. You may want to make the window.onpopstate function
    // below a named function, and just call that function here.
  }

  // You can of course have code execute in all three cases. It would go here.

  // You may also wish to set the history state at this time. This could go in the
  // if..else statement above if you only want to replace the state in certain
  // circumstances. One reason for setting the state right away would be if the user
  // navigates to your page via a deep link.
  let state = ...; // There might not be much to set at this point since the page was
                   // just loaded, but if your page gets random content, or time-
                   // dependent content, you may want to save something here so it can
                   // be retrieved again later.
  let title = ...; // Since this isn't actually used by your browser yet, you can put
                   // anything you want here, though I would recommend setting it to
                   // null or to document.title for when browsers start actually doing
                   // something with it.
  let URL = ...;   // You probably don't want to change the URL just yet since the page
                   // has only just been loaded, in which case you shouldn't use this
                   // variable. One reason you might want to change the URL is if the
                   // user navigated to this page with a query string in the URL. After
                   // reading the query string, you can remove it by setting this
                   // variable to: location.origin + location.pathname
  history.replaceState(state, title, URL); // Since the page has just been loaded, you
                                           // don't want to push a new state; you should
                                           // just replace the current state.
}

// This function is called when navigating between states that you have set.
// Since the purpose of `history` is to allow dynamic content changes without
// reloading the page (ie contacting the server), the code in this function
// should be fairly simple. Just things like replacing text content and images.
window.onpopstate = function() {
  // Do things with history.state here.
}

// This function is called right before the page is refreshed, and right
// before leaving the page (not counting history.replaceState). This is
// your last chance to set the page's history state before leaving.
window.onunload = function() {
  // Finalize the history state here.
}

请注意,我从未在任何地方调用过 history.pushState。这是因为不应在这些函数的任何地方调用 history.pushState。它应该由以某种方式实际更改页面的函数调用,您希望用户能够使用后退按钮撤消。

总而言之,通用设置可能会像这样工作:

  • window.onload函数中勾选if (history.state == null)
    • 如果为真,则用新信息覆盖历史状态。
    • 如果为false,则使用历史状态恢复页面。
  • 当用户浏览页面时,当发生重要事情时调用 history.pushState 应该可以使用后退按钮撤消。
  • If/When 用户使用他们的后退按钮并触发 popstate 事件,使用您设置的历史状态 return 将页面恢复到之前的状态。
    • 同样做 if/when 用户然后使用他们的前进按钮。
  • 使用 unload 事件在用户离开页面之前完成历史记录状态。