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

如何在Angular或JavaScript中检测Chrome是否处于隐身模式?

检测Google Chrome隐身模式的Angular/JavaScript实现方法

你贴的那段基于webkitRequestFileSystem的代码已经失效了——Chrome后续版本调整了隐身模式的文件系统权限逻辑,这个API不再能用来区分普通模式和隐身模式。下面是目前可行的检测方案:

可行检测方案

1. 原生JavaScript实现

利用隐身模式下IndexedDB写入失败的特性:

function checkIncognitoMode() {
  return new Promise((resolve) => {
    const testDbName = 'IncognitoModeCheck';
    const dbRequest = indexedDB.open(testDbName);

    dbRequest.onupgradeneeded = () => {
      // 普通模式下能正常创建数据库,清理后返回false
      dbRequest.result.close();
      indexedDB.deleteDatabase(testDbName);
      resolve(false);
    };

    dbRequest.onerror = () => {
      // 隐身模式下创建数据库会触发错误,返回true
      resolve(true);
    };
  });
}

// 使用示例
checkIncognitoMode().then(isIncognito => {
  console.log(isIncognito ? '当前处于隐身模式' : '当前未处于隐身模式');
});

2. Angular中的封装实现

可以把检测逻辑封装成服务,方便组件调用:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class IncognitoCheckService {
  checkIncognito(): Promise<boolean> {
    return new Promise((resolve) => {
      const testDbName = 'AngularIncognitoCheck';
      const dbRequest = indexedDB.open(testDbName);

      dbRequest.onupgradeneeded = () => {
        dbRequest.result.close();
        indexedDB.deleteDatabase(testDbName);
        resolve(false);
      };

      dbRequest.onerror = () => {
        resolve(true);
      };
    });
  }
}

在组件中调用:

import { Component, OnInit } from '@angular/core';
import { IncognitoCheckService } from './incognito-check.service';

@Component({
  selector: 'app-root',
  template: `<p>当前浏览器模式:{{ modeLabel }}</p>`
})
export class AppComponent implements OnInit {
  modeLabel = '';

  constructor(private incognitoService: IncognitoCheckService) {}

  ngOnInit() {
    this.incognitoService.checkIncognito().then(isIncognito => {
      this.modeLabel = isIncognito ? '隐身模式' : '普通模式';
    });
  }
}

注意事项

  • 这类检测手段依赖浏览器的隐私权限限制,未来Chrome如果调整相关策略,可能会失效
  • 检测是异步操作,必须通过Promise或async/await处理结果
  • 不要过度依赖该功能,浏览器厂商一直在强化隐私保护,这类检测逻辑随时可能被封堵

内容的提问来源于stack exchange,提问作者Rishabh Verma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:53:12