I want to change the function of the "back" browser button. I tried with this:

我想更改“后退”浏览器按钮的功能。我试过这个:

window.onbeforeunload = function() {
    show_page(last_page, 'not-search'); 
}

and it works, in part: it calls the function but the browser navigates to the previous page anyway. Is there a solution for that?

它的工作原理部分是:它调用函数,但浏览器无论如何都会导航到上一页。有解决方案吗?

EDIT I need to do that:

index(ajax content) ---user click--->other ajax content(i call it A content)
A content --->back button ---->previous index content

编辑我需要这样做:index(ajax内容)---用户点击--->其他ajax内容(我称之为A内容)一个内容--->后退按钮---->以前的索引内容

3 个解决方案

#1


1

Return a string in your function to warn the user and give the option to cancel.

在函数中返回一个字符串以警告用户并提供取消选项。

window.onbeforeunload = function() {
    show_page(last_page, 'not-search'); 
    return "please do not use the back button";
}

Completely disabling is both tricky and bad practise. Limiting the user in such a way could easily be seen as spam or unwanted behaviour.

完全禁用既棘手又不好。以这种方式限制用户很容易被视为垃圾邮件或不需要的行为。

edit

编辑

After I have read your edit, I would suggest to use history.pushState whenever you are modifying the page with ajax. That way the backbutton will navigate to an earlier state which is what you want. Take a look at the history API for all functions you need.

在我阅读了您的编辑后,我建议您在使用ajax修改页面时使用history.pushState。这样,后退按钮将导航到您想要的早期状态。查看所需功能的历史API。

When the previous button is pressed it will trigger window.onpopstate function where you can handle to load the correct content. See example below:

按下上一个按钮时,它将触发window.onpopstate函数,您可以在其中处理加载正确的内容。见下面的例子:

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

更多相关文章

  1. RegExp:匹配除Javascript中的正则表达式值之外的所有内容
  2. 如何禁用IE和Firefox中的后退按钮? [重复]
  3. 使用Jquery Ajax更改按钮的颜色(从外部PHP文件接收颜色)
  4. 从另一个数组中删除数组的内容。
  5. WebKit "拒绝设置不安全的标题'内容长度' "
  6. 根据下拉菜单的选择更改div的内容
  7. 在单选按钮上选中/取消选中,加载/隐藏部分视图
  8. java 如何获取动态网页内容,返回字符串
  9. 彻底解决IE8和IE9下ewebeditor上按钮无效的方法

随机推荐

  1. golang操作Redis&Mysql&RabbitMQ的方法介
  2. go语言实现日志收集系统图文详解
  3. go的websocket实现(附代码)
  4. go语言time包的一些使用方法
  5. go语言中的并发介绍(附代码)
  6. Go中string转[]byte的陷阱
  7. go语言中goroutine的使用详解
  8. go微服务框架go-micro整体架构介绍
  9. 完全掌握Go的pprof使用方法
  10. vscode中的Golang配置介绍