我可以使用后退按钮检测用户何时到达页面?

时间:2009-07-15 21:09:34

标签: javascript cross-browser

编辑:我真正需要知道的是,当用户通过后退按钮到达页面时,是否有任何javascript事件会可靠地触发。我为onload元素尝试了body事件,但它不会在Firefox或Safari上触发。


我正在处理一些旧代码,这些代码试图通过在用户单击一个表单时(通过监听表单的onSubmit事件)禁用所有表单提交按钮来阻止表单数据的双重提交。此代码适用于应用程序中的每个表单,无论双重提交是否会成为问题。

问题是如果用户点击Firefox或Safari中的后退按钮,当他到达页面时,所有提交按钮仍然被禁用。在Firefox上,它们甚至在刷新后被禁用(只有Ctrl + F5刷新才会这样做)!

我已尝试收听body的{​​{1}}事件,但当您通过后退按钮访问该页面时,FF和Safari不会触发。 (有趣的是,即使按钮保持禁用状态,它也会在FF上的软刷新时触发。)


这是一个非常简单的HTML文档,它将显示我的意思:

onLoad

注意:我已经使用IE8,FF3.5,Safari 4,Opera 9和Chrome 2.0在WinXP上进行了测试。只有Safari和FF在您使用返回时禁用该按钮。

4 个答案:

答案 0 :(得分:2)

这不是您想要的行为,因此他们不会使用后退按钮双重提交吗?

无论如何,你可以在下一页上设置一个cookie,并在页面上加载时检测表格。

答案 1 :(得分:2)

是。在javascript中,您可以使用visited.value

function checkrefresh()
 var visited = getCookie("visited");  
{
        if((form.visited.value == '' || form.visited.value == null) && (visited != '1') ) 
        {
            document.form.visited.value = "1";
                    document.cookie = "visited=1";
                    //here you set it to something so that next time they go to the page it will no longer be nothing and you can 'disable the button' see below.

        }
        else
        {
            document.form.submitbutton.disabled=true;
        }
    } 

function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}

你可以在onload标签FYI中调用它。

答案 2 :(得分:1)

我认为您不能专门测试后退按钮,但我相信您可以使用Javascript检查浏览器的历史记录位置。

答案 3 :(得分:0)

@tkotitan的答案在他写作时可能是正确的。他的回答使我得到了解决方案。这不是万无一失的,但在某些情况下帮助可能“足够好”。

我改进了我的脚本并将其替换为以下内容。此版本适用于中间页面,现在可以作为两个方向的中间页面。

<?php
if($_SERVER['QUERY_STRING']=='')
{
    echo '<a href="go_back_test.php?page=1">Go forward</a>';
}
elseif($_GET['page']!=2)
{
    echo 'You cannot stay here.';
    echo '
    <script type="text/javascript">
    function test()
    {
        if (document.getElementById("detectback").value=="goneback")
        {
            document.getElementById("detectback").value=history.length;
        }
        if (document.getElementById("detectback").value==history.length)
        {
            document.getElementById("detectback").value="goneforward";
            window.location = "go_back_test.php?page=2"
        }
        else
        {
            document.getElementById("detectback").value="goneback";
            window.history.back();
        }
    }
    function updateform()
    {
        if(document.getElementById("detectback").value=="")
        {
            document.getElementById("detectback").value=history.length;
        }
    }
    </script>
    <img src="spacer.gif" onload="updateform(); test();"><br>
    <form>
        <input id="detectback" type="text" value="" style="display: none;">
    </form>
    ';
}
else
{
    echo 'Welcome to page 2';
}
?>
相关问题