You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止history.back()执行时回退到外部网站?

history.back() 禁止回退到外部站点的实现方案

history.back() 本身是按照浏览器全局历史记录栈的顺序回退,默认不会区分站内/站外页面,要实现仅在站内回退的效果,可通过以下两种方案实现:

方案1:基于referrer判定的轻量实现

核心逻辑是判断上一个访问来源是否和当前站点同域,符合条件则执行回退,否则跳转至站内指定页面(比如首页):

function customBack() {
  const currentDomain = window.location.origin;
  // 判断上一页是否来自本站
  if (document.referrer && document.referrer.startsWith(currentDomain)) {
    history.back();
  } else {
    // 外部来源或直接打开站点时,跳转至站内首页,也可替换为其他站内路径
    window.location.href = '/';
  }
}

按钮调用方式:

<button onclick="customBack()">返回</button>

方案2:自行维护站内历史栈(更稳定,适合单页应用)

如果是SPA类站点,可完全不依赖浏览器原生历史栈,自行在sessionStorage中维护站内访问记录,回退时直接从自定义栈中读取路径跳转,从根源上避免跳转到外部站点:

// 每次站内路由跳转时调用,存入当前访问路径
function saveInnerHistory(path) {
  const historyStack = JSON.parse(sessionStorage.getItem('innerHistory') || '[]');
  historyStack.push(path);
  sessionStorage.setItem('innerHistory', JSON.stringify(historyStack));
}

// 自定义返回逻辑
function customBack() {
  const historyStack = JSON.parse(sessionStorage.getItem('innerHistory') || '[]');
  if (historyStack.length > 1) {
    // 弹出当前路径,跳转至上一个站内路径
    historyStack.pop();
    const prevPath = historyStack.pop();
    window.location.href = prevPath;
  } else {
    // 无站内历史记录时跳转首页
    window.location.href = '/';
  }
}

注意事项

  • document.referrer可能会因为浏览器隐私策略、站点Referrer Policy配置等原因为空,此时默认走站内跳转逻辑即可,不影响功能可用性。
  • 如果业务场景允许,也可以在判定上一页为外部站点时直接隐藏返回按钮,避免给用户造成不必要的误导。

内容的提问来源于stack exchange,提问作者A-d-ash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:21:02