是否存在检测最后一次导航事件是否由后退或前进浏览器按钮引起的方法

Is there anyway to detect if the last navigation event was caused by the back or forward browser buttons?

本文关键字:是否 浏览器 按钮 方法 最后一次 检测 存在 导航 事件      更新时间:2023-09-26

我正在编写一个单页web应用程序,使用HTML5推送状态(回落到散列标签)来处理客户端导航。

我注意到的一件事是,如果用户向下滚动页面,然后点击到另一个页面的链接,当他们导航到那个页面时,浏览器仍然会保持在滚动的位置。

我想,如果你去一个新的页面,它会平滑滚动你到顶部(相同的行为当所有的网站点击链接)。

我在我的导航控制器中使用了一点jquery动画实现了这一点,我现在的问题是,如果你点击浏览器的后退按钮,你不会在你之前的滚动位置结束,相反,你会在上一页,但你会滚动到顶部。

是否有可能检测到上次/当前客户端导航是由浏览器的后退或前进按钮引起的?如果是这样,我将使用它来防止滚动。

欢呼

据我所知,你只能抓住"我的应用程序更改了标签"answers"浏览器强制更改标签"之间的区别。

我是这样检查的:

当你的控制器用它的新标签推送一个新的状态(打开一个页面)时,在你将它设置为window.location.hash之前,将这个新标签存储在一个全局javascript变量中。当您捕捉到'hashchange'事件时,然后将此全局变量与window.location.hash进行比较。如果全局变量与新的散列标签相同,则意味着您的应用程序只是更改了散列本身(并打开了一个新页面)。如果未设置全局变量,则表示浏览器强制导航。但是,您无法知道浏览器强制导航是因为地址栏编辑还是因为后退/前进按钮。

考虑以下代码:

// Global hashtag variable, used to compare state changes
var gCurrentHash = window.location.hash;
// Called when hashtag is changed by the browser
function onHashChange(event)
{
    var hash_tag = window.location.hash;
    if (hash_tag != gCurrentHash)
    {
        // Browser forced navigation
    }
    else
    {
        // App caused navigation
    }
}
window.addEventListener('hashchange', onHashChange, false);
在控制器中,在更新散列标签之前,调用以下代码:
gCurrentHash = window.location.hash;

在您实际更改window.location.hashtag之前调用它是非常重要的!

[edit]你可以试试这个选择:将标签更改的历史记录存储在cookie中,并比较这些更改。根据这些信息,您可以估计后退/前进导航事件

我想要一个网站,我正在工作的当前响应相同,无论用户在特殊的ajax识别散列标签类型,书签它或点击相应的页面链接。因此,我查看标签本身的模式,并在需要时强制导航。

例如:

var myDefaultPageName = "myAjaxPage1";
// hash tags in this domain may indicate ajax page navigation
// using '#!' to indicate ajax links however, allowing user to type in 
// hashtag without '!' so function understands both '#!myAjaxPage1' and
// '#myAjaxPage1' as ajax requests, the pattern of the hashtag will be
// checked to determine if ajax navigation is needed
function processHashtagChange() {
    // note: bookmarked urls may be #! or #, need to understand both
    var startIndex = 1; // skip '#'
    if (location.hash.charAt(1) == '!') { // check for special '#!' ajax prefix
        startIndex++;
    }
    // extract ajax pagename from hash
    var pagename = location.hash.substring(startIndex); 
    var regex = "."; // match everything for now, hash tags 
                     // only used for ajax navigation here
    if (pagename.length == 0) // default to something if needed, allows 
    {                         // back button to http://mydomain.com to load 
                              // default ajax page
        pagename = myDefaultPageName;
    }
    if (pagename.match(regex)) { // does this hash indicate ajax navigation
        var pageurl = '/?page=' + pagename;    
        loadPageViaAjax(pageurl); // update the dom via ajax
    }
}