检测浏览器历史记录

时间:2014-05-02 12:13:10

标签: javascript

在这个问题上有很多帖子,有些会导致一个解决方案,但其中没有一个似乎适合我。

我想知道用户何时按下浏览器上的后退按钮,以便我可以采取适当的操作。但按下按钮时没有任何反应。我现在已经尝试了几天,希望有人可以发光。 这是我的js代码

function browserButtonEvent() {
    if(window.event) {
        if(window.event.clientX < 40 && window.event.clientY < 0) { //ie

        } 
        else 
        {
            alert("navigation button clicked");
        }
    }
    else {

        if(event.currentTarget.performance.navigation.type == 1) {
            alert("Refreshed");         
        }
        if(event.currentTarget.performance.navigation.type == 2) {
            alert("Back button pressed");
        }
    }
}

这是我的测试html页面。 (我还有2个页面,但我认为其中一个应该足够了)

                                        
    

<body onbeforeunload="browserButtonEvent()">
    <h3>Index</h3>
    <div style="margin-left: auto; margin-right: auto; width: 600px; height: 600px; background-color: lightblue; margin-top: 200px;">
        <form action="">
            <input type="button" value="Press" onclick="goHistory()"/>
            <br />
            <!--<input type="button" value="Test" id="test" />-->
            <br />
            <a href="page2.html">Page 2 </a>
            <br />
            <a href="page3.html">Page 3 </a>
            <p>Page 1</p>

            <div style="margin-left: auto; margin-right: auto; width: 150px;">
                <a id="back" style="float: left;">Back</a> 
                <a id="forward" style="float: right;">Forward</a>
            </div>

        </form>
    </div>
</body>

2 个答案:

答案 0 :(得分:0)

您可以尝试使用onbeforeonunload

window.onbeforeunload = function () {
   browserButtonEvent();
};

虽然有一个问题。后退按钮和resfresh按钮都将调用此功能。当我遇到同样的问题时,这就是我走了。

答案 1 :(得分:0)

您可以试试这个,但可能需要对整个网站/应用程序进行更改: http://benalman.com/projects/jquery-bbq-plugin/

相关问题