【问题标题】:How to prevent history.back() to return back to external website?如何防止 history.back() 返回外部网站?
【发布时间】:2021-11-07 11:53:12
【问题描述】:

所以我尝试使用onclick="history.back()" 制作后退按钮。但问题是当我使用外部链接进入我的网站并按下后退按钮时,它会将我带回到上一个外部页面。我知道它已被编程为这样做。但是有什么办法可以阻止它把用户带回外部网站呢?

【问题讨论】:

  • 我希望这是不可能的,因为我不希望我访问的随机网站能够看到我的浏览器历史记录。
  • @djones 为什么他们需要查看您浏览器的历史记录才能执行此操作?他们所要求的实际上比当前模型更安全:History API 的源隔离。

标签: javascript html html5-history


【解决方案1】:

一种方法是将您第一次访问页面时收到的history.length 值存储在sessionStorage 中。

然后将当前索引存储在history.state 中。一旦您返回初始索引,您将阻止历史返回。

// To be executed on all the pages of your domain

// check if we already saved it
let min_index = sessionStorage.getItem("minHistoryIndex");
// otherwise
if (min_index === null) {
  // store it
  min_index = history.length;
  sessionStorage.setItem("minHistoryIndex", min_index);
}
// first time we come to this history status
if (!history.state ) {
  history.replaceState({ index: history.length }, "");
}

const button = document.querySelector("button");
// if we reached the limit saved in sessionStorage
if (history.state.index === +min_index) {
  button.disabled = true;
  button.title = "Going back once more would take you out of our website";
}
else {
  button.onclick = (evt) => history.back();
}

Live demo - source

这样做的一个问题是,如果您的用户决定从您的页面转到其他来源,然后手动返回,您可以返回该外部域,但我想这是一个极端情况,它可以在大多数情况下被接受。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多