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

Cordova Electron 3.1.0集成@journeyapps/sqlcipher时window.require报错求助

解决方案

核心原因

cordova-electron 3.x 对应的 Electron 版本(通常为v12+)默认开启了Context Isolation(上下文隔离),即便你设置了nodeIntegration: true,渲染进程也无法直接访问window.require——这是Electron为提升安全性引入的变更。而旧版本cordova-electron 1.1.1对应的Electron版本较低,默认关闭了该特性,因此能正常运行。


方案1:关闭Context Isolation(快速临时解决)

在Electron的BrowserWindow配置中,同时开启nodeIntegration并关闭contextIsolation:

  • 若通过config.xml配置cordova-electron:
<preference name="ElectronPreferences" value='{"webPreferences": {"nodeIntegration": true, "contextIsolation": false}}' />
  • 若自定义Electron主进程代码:
const { BrowserWindow } = require('electron');

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

修改后重新构建应用,window.require即可正常使用。

方案2:使用预加载脚本(推荐,符合Electron安全规范)

这是Electron官方推荐的安全实践,通过预加载脚本在主进程与渲染进程间建立安全通信桥:

  1. 在项目根目录创建preload.js文件:
const { contextBridge } = require('electron');
const sqlcipher = require('@journeyapps/sqlcipher').verbose();

// 向渲染进程暴露sqlcipher对象
contextBridge.exposeInMainWorld('sqlcipher', sqlcipher);
  1. 配置BrowserWindow的preload路径:
  • 通过config.xml配置:
<preference name="ElectronPreferences" value='{"webPreferences": {"preload": "./preload.js", "nodeIntegration": false, "contextIsolation": true}}' />
  • 或自定义主进程代码:
const { BrowserWindow } = require('electron');
const path = require('path');

const mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
    nodeIntegration: false,
    contextIsolation: true
  }
});
  1. 在React代码中直接使用暴露的对象:
// 替换原window.require调用
const db = window.sqlcipher.Database('path/to/your/db');

方案3:重新编译依赖适配Electron版本

若上述方案无效,可能是@journeyapps/sqlcipher未适配当前cordova-electron对应的Electron版本,尝试重新安装并编译依赖:

rm -rf node_modules package-lock.json
npm install
npx cordova platform remove electron
npx cordova platform add electron@3.1.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:25:22