javascript - 保留 window.history.back() 以供以后使用

标签 javascript jquery browser-history

我正在结账,我有一个后退按钮,点击后会触发 window.history.back()

工作正常,直到用户在购物车中进行一些更改,然后页面重新加载和 window.history.back() 的作用与 window.reload() 相同,因为它获取最后一页。

我知道最好的解决方法是通过用户输入将 Ajax 应用于此购物车更新,以在进入购物车之前保持 window.history.back() 与上一页不可变。但这在这个项目上是不可能的,它是一个临时的 prestashop,在提交之前单击某些修改按钮时保留 window.history.back() 就可以了,以保持后退按钮的功能。

我认为由于隐私原因这是不可能的,但我想知道以前是否有人遇到过这个问题以及哪种解决方法会更好。

使用 history.go(-2) 会向用户发送后退两步的信息,因此对于某些用例来说这是不行的。

也许将全局计数器设置为 -1 ,然后在进入或重新加载购物车时设置为 --counter; 可以使用 history.go(counter) 来解决问题;

对于处理这种情况有什么建议吗? 谢谢。

最佳答案

使用以下解决方法已解决:

代码:

/* inside the page where we want to preserve the "back" URI */
  <script>
var counter = 0;
      if(window.name != ""){
/* if window.name is set, assign the value to var counter*/
          counter = window.name;
      } else {
/* if it's not, init to 0. */
          counter = 0;
      }
/* Set window.name to counter value minus 1. It will be set to -1 the first time you enter the cartPage (on this example case) and it will be changed to -2, -3 etc each time you reload. */
      window.name = counter-1;
  </script>
/* On global.js */

if(window.location.href.indexOf("cartPage") === -1) {
    /* Reset window.name value if we're not on cartPage, to avoid errors */
    window.name = "";
}

/* The button: */

<a onclick="history.go(window.name)"> go back </a>

希望它对某人有帮助。 干杯!

关于javascript - 保留 window.history.back() 以供以后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52382660/

相关文章:

javascript - jQuery 选择器按类生成错误

c# - 检索 Windows Mobile 浏览器历史记录

javascript - 创建自定义 html 元素时未调用连接的回调

javascript - Chrome 扩展程序 - 请求当前选项卡的可选权限

Jquery 按索引选择元素

javascript - 获取ajax历史

powershell - 使用 powershell 的浏览器历史记录

javascript - 传递到 Facebook 购买事件时 GTM Datalayer 变量未定义

javascript - ExtJS4 变换组合框 onchange() 事件不起作用

php - 将 smarty bool 值转换为人类可读的值。 ('Yes'/'No' 或 'True'/'False' )