electron 电子弹出窗口($未定义);控制台日志中没有错误

ycggw6v2  于 2022-12-08  发布在  Electron
关注(0)|答案(1)|浏览(270)

简而言之:我正在使用Electron实现一个单页网站,遇到了jQuery不能全局访问的常见问题。因此,我使用下面的快速入门示例简化了这个问题,以便解决它,但我无法理解它。
如您所见,我只是将以下代码添加到main.js文件的末尾,以检查问题是否得到解决:

$(document).ready(function () {
    console.log("hi");
});

下面是我的main.js文件的完整代码:

// main.js
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require("electron");
const path = require("path");

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
        preload: path.join(__dirname, "preload.js"),
        nodeIntegration: true,

        webSecurity: true,
    },
    });

    // and load the index.html of the app.
    mainWindow.loadFile("index.html");

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    createWindow();

    app.on("activate", function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

// Quit when all windows are closed.
app.on("window-all-closed", function () {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== "darwin") app.quit();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

$(document).ready(function () {
    console.log("hi");
});

我将以下HTML代码加载到我的BrowserWindow中:

<!DOCTYPE html>
<html>
    <head>

    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->

    <!--This was added otherwise "window.jQuery = window.$ = require('jquery');" will not be executed-->
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />

    <title>Hello World!</title>
    </head>
    <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.

    <script src="node_modules/jquery/dist/jquery.min.js"></script>
    <script>window.jQuery = window.$ = require('jquery');</script>
    <script src="./renderer.js"></script>

    </body>
</html>

根据电子文档的建议,以下脚本作为preload脚本附加到BrowserWindow

// Preload.js
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
window.addEventListener("DOMContentLoaded", () => {
    const replaceText = (selector, text) => {
    const element = document.getElementById(selector);
    if (element) element.innerText = text;
    };

    for (const type of ["chrome", "node", "electron"]) {
    replaceText(`${type}-version`, process.versions[type]);
    }
});

最后但并非最不重要的是,这是快速入门项目的package.json配置文件:

{
    "name": "electron-quick-start",
    "version": "1.0.0",
    "description": "A minimal Electron application",
    "main": "main.js",
    "scripts": {
        "start": "electron ."
    },
    "repository": "https://github.com/electron/electron-quick-start",
    "keywords": [
        "Electron",
        "quick",
        "start",
        "tutorial",
        "demo"
    ],
    "author": "GitHub",
    "license": "CC0-1.0",
    "devDependencies": {
        "electron": "^9.0.2"
    },
    "dependencies": {
        "jquery": "^3.5.1"
    }
}

但是,每次运行应用程序时,我都会收到以下错误提示:

这个错误也显示在我的应用程序的Powershell输出中(我只编辑了完整的目录路径):

App threw an error during load
ReferenceError: $ is not defined
  at Object.<anonymous> (...directory\0masterproject\main.js:48:1)
  at Module._compile (internal/modules/cjs/loader.js:967:30)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1004:10)
  at Module.load (internal/modules/cjs/loader.js:815:32)
  at Module._load (internal/modules/cjs/loader.js:727:14)
  at Function.Module._load (electron/js2c/asar.js:738:28)
  at loadApplicationPackage (...directory\0masterproject\node_modules\electron\dist\resources\default_app.asar\main.js:109:16)    at Object.<anonymous> (...directory\0masterproject\node_modules\electron\dist\resources\default_app.asar\main.js:155:9)
  at Module._compile (internal/modules/cjs/loader.js:967:30)
  at Object.Module._extensions..js (internal/modules/cjs/loader.js:1004:10)
PS ...directory\0masterproject> npm start

然而,当我关闭这个窗口并检查BrowserWindow的控制台时,我没有看到任何错误,也没有“hi”输出。
在遇到这个问题之前,我遇到了require ()没有定义的问题,我通过添加

<script src="node_modules/jquery/dist/jquery.min.js"></script>

在我jQuery代码之前:

<script>window.jQuery = window.$ = require('jquery');</script>

我在this article中找到了这个解决方案;我已经在Electron的文档中尝试过这个例子,但是没有效果。
如有任何信息缺失,请告知我。

bvpmtnay

bvpmtnay1#

你把你的main and renderer processes搞混了。对于Electron,所有负责UI的代码,即附加到BrowserWindow中加载的HTML的JavaScript在渲染器进程中运行,所有其他代码,例如,负责打开窗口或设置app的代码在主进程中运行。
在这个主进程中,您不能使用DOM特定的全局变量,因为主进程是一个纯粹的Node.js。

$(document).ready(function () {
  console.log("hi");
});

同样,主进程“environment is detached from your renderer process”(这就是为什么你必须使用IPC在它们之间通信),因此$没有在你的main.js中定义,因为你在renderer HTML中定义了它。
如果您改为将以下代码放在HTML文件的末尾(或者甚至将renderer.js放在HTML文件的最末尾),您可能会得到所需的结果:

<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script>
    window.jQuery = window.$ = require('jquery');
    const $ = window.jQuery;
    $(document).ready(function () {
        console.log("hi");
    });
</script>
<script src="./renderer.js"></script>

毕竟,我建议您通过深入研究Electron的文档(如this article)来熟悉Electron架构,因为如果不熟悉main/renderer的设计原理,就不会有太多问题,只需了解此设计即可轻松解决。

相关问题