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

如何获取浏览器首次加载文档的Referrer,以正确控制取消按钮显示?

解决方案

方案1:通过URL参数传递模式标识

在Java应用打开报告页面时,根据当前运行模式(桌面/远程)在URL中添加模式参数:

  • 桌面模式:打开 http://local:4567/report1.html?mode=desktop
  • 远程模式:打开 http://nas-ip:4567/report1.html?mode=remote

然后在所有报告页面的JS中读取该参数,控制按钮显示:

document.addEventListener('DOMContentLoaded', () => {
  const params = new URLSearchParams(window.location.search);
  const isDesktop = params.get('mode') === 'desktop';
  document.getElementById('cancel-button').style.display = isDesktop ? 'none' : 'block';
});

注意:生成多页报告的跳转链接时,要自动带上mode参数,比如跳转链接写成 report2.html?mode=${params.get('mode')},确保后续页面能获取到模式标识。

优点:逻辑简单直接,无需依赖浏览器存储或referrer,兼容性好。
缺点:需要Java应用在打开页面时动态添加参数,且报告内的跳转链接需处理参数传递。

方案2:利用SessionStorage保存初始模式状态

通过首次加载页面的document.referrer判断初始模式,将状态存入SessionStorage,后续页面直接读取该状态:

document.addEventListener('DOMContentLoaded', () => {
  const cancelBtn = document.getElementById('cancel-button');
  let isRemote = sessionStorage.getItem('isRemote');

  if (!isRemote) {
    // 首次加载时判断初始来源
    const referrer = document.referrer;
    // 远程模式下,报告页面来自应用起始页(同域);桌面模式下referrer为空
    isRemote = referrer && new URL(referrer).hostname === window.location.hostname ? 'true' : 'false';
    sessionStorage.setItem('isRemote', isRemote);
  }

  cancelBtn.style.display = isRemote === 'true' ? 'block' : 'none';
});

优点:无需修改Java生成报告的逻辑,纯前端实现,适配单份报告多场景使用。
缺点:若用户直接打开报告子页面(而非从首页进入),初始状态判断可能出错;SessionStorage在浏览器会话结束后失效。

方案3:通过页面域名/主机名判断模式

根据当前页面的主机名区分桌面与远程模式:

document.addEventListener('DOMContentLoaded', () => {
  const cancelBtn = document.getElementById('cancel-button');
  // 桌面模式下使用本地主机名(如localhost、127.0.0.1、local)
  const isDesktop = ['localhost', '127.0.0.1', 'local'].includes(window.location.hostname);
  cancelBtn.style.display = isDesktop ? 'none' : 'block';
});

优点:完全独立,无需依赖任何外部参数或存储,单份报告即可适配两种场景。
缺点:需确保桌面模式与远程模式的主机名有明确区分,若桌面模式使用自定义主机名,需同步更新判断列表。


内容的提问来源于stack exchange,提问作者Paul Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:10:13