保留 window.history.back() 以备后用

Preserve window.history.back() to use later

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

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

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

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

使用 history.go(-2) 将向用户发送后退两步,因此对于某些用例来说是不合适的。

也许将全局计数器设置为 -1,然后在进入或重新加载购物车时将 --counter; 设置为 history.go(counter);

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

尝试

window.location.replace(document.referrer);

使用以下解决方法解决

代码:

/* 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>

希望对大家有所帮助。 干杯!