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

Electron集成Flask应用时jQuery报错:$ is not defined等问题求助

解决方案
  • 修正静态资源路径适配Electron环境
    浏览器中Flask的/bootstrap/static/路径基于服务器根目录,但Electron加载本地文件遵循文件系统路径规则。将HTML中jQuery的引用路径从绝对路径改为相对路径(根据HTML与静态资源的实际层级调整):

    <!-- 原路径 -->
    <script src="/bootstrap/static/jquery.min.js"></script>
    <!-- 修改后 -->
    <script src="./bootstrap/static/jquery.min.js"></script>
    

    加载HTML时也可通过__dirname动态生成完整file协议路径:

    mainWindow.loadURL(`file://${path.join(__dirname, 'dist', 'index.html')}`);
    
  • 强制暴露jQuery全局变量
    部分场景下jQuery以模块形式加载,不会自动挂载到window对象,导致Bootstrap无法识别$。在引入jQuery的脚本后添加强制挂载代码(需在Bootstrap脚本之前执行):

    <script src="./bootstrap/static/jquery.min.js"></script>
    <script>
      window.$ = window.jQuery = jQuery;
    </script>
    
  • 验证Electron窗口配置是否生效
    确认主进程中BrowserWindow的webPreferences配置正确设置,避免因配置位置错误导致失效:

    const { BrowserWindow, path } = require('electron');
    
    const mainWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        webSecurity: false, // 禁用本地资源跨域安全检查
        allowRunningInsecureContent: true
      }
    });
    
  • 检查PyInstaller打包的静态资源完整性
    确保PyInstaller将静态资源正确打包,使用--add-data参数指定资源目录:

    pyinstaller --add-data "bootstrap/static:bootstrap/static" your_flask_entry.py
    

    打包完成后,查看输出目录(如dist)下是否存在完整的bootstrap/static目录及jQuery文件。

  • 用Preload脚本注入jQuery(替代方案)
    若不想开启nodeIntegration,可通过Preload脚本安全注入:

    1. 创建preload.js:
      const { contextBridge } = require('electron');
      const $ = require('./bootstrap/static/jquery.min.js');
      contextBridge.exposeInMainWorld('$', $);
      contextBridge.exposeInMainWorld('jQuery', $);
      
    2. 在BrowserWindow配置中指定Preload脚本:
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js')
      }
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:43:19