如果URI不变,例如如何检测用户是否在新页面上在单页应用程序上?

时间:2018-07-14 13:14:01

标签: javascript

我需要能够检测用户何时访问了同一网站中的新页面。例如,他转到索引页面,然后导航到联系人页面。

我需要使用JS进行此检测。

如果每个页面都有一个单独的URI,那么一切都很好,但是我发现很多网站,尤其是SPA,在用户浏览时都不要更改URI。所以一切都是/

我的问题是:还有另一种方法可以检测用户何时导航到其他页面?例如,是否有一些窗口或文档值可以告诉我这是一个唯一页面?

1 个答案:

答案 0 :(得分:0)

根据浏览器兼容性要求,您可以使用the history API来模拟和跟踪页面导航,而无需加载整个页面。

历史API示例

从Mozilla MDN:

history.replaceState(stateObj, "page 3", "bar2.html");
  

这将导致URL栏显示http://mozilla.org/bar2.html,   但不会导致浏览器加载bar2.html甚至不会检查   bar2.html存在。

通过使用replaceState及其同级功能pushState模拟导航,可以使用window.onpopstate事件检测导航。

再次是window.onpopstate的示例,from MDN

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}

旧版替代方法:使用location.hash(#)

对于旧版浏览器,某些SPA,例如Google Maps使用window.location.hashwindow.onhashchange事件实现了类似的行为。这些通常以“ hashbang”片段标识符的形式出现,例如#!/some/page.html,一种流行于Google proposal的格式,但是存在quite compelling reasons的一种格式,因为它没有将其用作路由机制。由于我们对History API进行了改进,因此尤其如此。