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

React JS(CRA)如何检测用户使用浏览器URL还是Electron/Nativefier桌面端

检测访问环境并禁止浏览器访问的实现方案

一、Electron 环境检测

Electron 运行时会在全局 window 对象上注入特定标识,可通过这些标识判断是否在 Electron 桌面端:

实现代码

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    const isElectron = () => {
      // 方式1:判断 window 是否存在 electron 专属属性
      const hasElectronProps = window.electron || window.require;
      // 方式2:通过 User Agent 特征检测
      const hasElectronUA = navigator.userAgent.toLowerCase().includes('electron');
      
      return hasElectronProps || hasElectronUA;
    };

    if (!isElectron()) {
      // 非桌面端环境,直接替换页面内容禁止访问
      document.body.innerHTML = '<h1>请使用桌面客户端访问此应用</h1>';
      // 也可直接跳转至空白页
      // window.location.href = 'about:blank';
    }
  }, []);

  return (
    <div className="App">
      {/* 你的应用内容 */}
    </div>
  );
}

export default App;

二、Nativefier 环境检测

Nativefier 打包的应用会自动在 window 对象上添加 nativefier 属性,也可通过打包时自定义标识提升检测可靠性:

方式1:利用内置标识检测

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    const isNativefier = () => {
      // Nativefier 会注入专属的 window.nativefier 对象
      return !!window.nativefier;
    };

    if (!isNativefier()) {
      document.body.innerHTML = '<h1>请使用桌面客户端访问此应用</h1>';
    }
  }, []);

  return <div className="App">{/* 应用内容 */}</div>;
}

export default App;

方式2:打包时自定义标识(更可靠)

打包时通过 --user-agent 参数添加专属标识:

nativefier --user-agent "MyApp-Desktop/1.0.0" "https://your-app-url.com"

然后在 React 中检测该自定义标识:

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    const isDesktopClient = () => {
      return navigator.userAgent.includes('MyApp-Desktop/1.0.0');
    };

    if (!isDesktopClient()) {
      document.body.innerHTML = '<h1>请使用桌面客户端访问此应用</h1>';
    }
  }, []);

  return <div className="App">{/* 应用内容 */}</div>;
}

export default App;

三、通用注意事项

  • 以上方案针对普通用户足够,但无法完全阻止技术人员伪造标识,若需更高安全性,可结合后端验证(比如桌面端携带专属密钥请求接口)。
  • 建议在 React 入口文件的最外层逻辑中提前执行检测,避免应用内容短暂暴露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:40:43