且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测用户是否使用后退按钮访问了某个页面?

更新时间:2023-12-02 13:47:10

使用隐藏表单.当您重新加载或点击后退按钮返回页面时,表单数据(通常)会保留在浏览器中.您的页面中包含以下内容(可能靠近底部):

Use a hidden form. Form data is preserved (typically) in browsers when you reload or hit the back button to return to a page. The following goes in your page (probably near the bottom):

<form name="ignore_me">
    <input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>

在您的 javascript 中,您将需要以下内容:

In your javascript, you will need the following:

var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') window.location.reload();
function mark_page_dirty() {
    dirty_bit.value = '1';
}

嗅探表单的 js 必须在 html 完全解析后执行,但如果用户延迟是一个严重问题,您可以将表单和 js 内联放在页面顶部(js 秒).

The js that sniffs the form has to execute after the html is fully parsed, but you could put both the form and the js inline at the top of the page (js second) if user latency is a serious concern.