无论如何检测上次导航事件是由后退还是前进浏览器按钮引起的?

时间:2011-11-30 06:43:05

标签: javascript html html5 hashbang

我正在编写一个单页Web应用程序,它使用HTML5推送状态(回退到哈希标签)来处理客户端导航。

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

我希望如果您进入新页面,它会平滑地滚动到顶部(跟随链接时所有网站的行为相同)。

我在导航控制器中用一个小的jquery动画实现了这一点,我现在遇到的问题是,如果你单击浏览器后退按钮,你不会最终处于你以前的滚动位置,而是你将在上一页,但您将滚动到顶部。

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

干杯

2 个答案:

答案 0 :(得分:0)

据我所知,你只能抓住“我的应用程序更改主题标签”与“浏览器强制标签更改”之间的区别。

这是我检查它的方式:

当您的控制器使用其新主题标签推送新状态(打开页面)时,请在将新主题标签设置为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中并比较更改。根据该信息,您可以估算后退/前进导航事件。

答案 1 :(得分:0)

我想要一个我正在努力的网站,无论用户是否输入特殊的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
    }
}