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

已引入jQuery却提示'jQuery is not defined'的问题求助

解决Electron中jQuery未定义的问题

核心原因

Electron渲染进程默认启用上下文隔离(contextIsolation),该机制会限制全局变量的跨上下文访问——即便你在HTML中按顺序加载了jQuery,自定义脚本也可能无法获取到全局的jQuery或$对象。


具体解决方法

方法1:调整BrowserWindow配置(快速验证,注意安全风险)

在创建主窗口时,关闭上下文隔离并启用Node.js集成:

const { BrowserWindow } = require('electron');
const path = require('path');

const mainWindow = new BrowserWindow({
  webPreferences: {
    contextIsolation: false,
    nodeIntegration: true
  }
});

注意:关闭上下文隔离会降低应用安全性,仅建议在开发环境或完全信任的内部应用中使用。

方法2:使用预加载脚本(推荐,安全合规)

通过Electron预加载脚本,在保持上下文隔离的前提下,安全地将jQuery暴露给渲染进程:

  1. 先通过npm安装jQuery:
npm install jquery --save
  1. 创建preload.js文件:
const { contextBridge } = require('electron');
const $ = require('jquery');

// 向渲染进程全局暴露jQuery
contextBridge.exposeInMainWorld('jQuery', $);
  1. 在BrowserWindow配置中指定预加载脚本路径:
const mainWindow = new BrowserWindow({
  webPreferences: {
    contextIsolation: true, // 保持安全的上下文隔离
    preload: path.join(__dirname, 'preload.js') // 替换为你的preload文件实际路径
  }
});
  1. 在code.js中使用暴露的jQuery:
window.jQuery(document).ready(function () {
  function showView(viewName){
    window.jQuery('.view').hide();
    window.jQuery('#' + viewName).show();
  }
  console.log('test');
});

方法3:排查jQuery加载有效性

确认CDN资源是否正常加载:

  • 打开开发者工具「Network」标签,查看jquery.min.js的请求状态,若返回非200码,说明CDN加载失败。
  • 改用本地jQuery文件:下载jQuery到项目js目录,修改HTML加载路径:
<head>
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script src="js/code.js"></script>
</head>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:22:46