【问题标题】:Electron pop up window ($ is not defined); No error in console log电子弹窗($未定义);控制台日志中没有错误
【发布时间】:2020-09-24 00:10:05
【问题描述】:

简而言之:我正在使用 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>

按照 Electron 文档的建议,以下脚本作为 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 找到了这个解决方案;我已经尝试过this example in Electron's documentation,但无济于事。

如果有任何信息缺失,请告诉我。

【问题讨论】:

  • 这能回答你的问题吗? Electron: jQuery is not defined
  • 是的!在大多数情况下。 @AlexanderLeithner 说我需要更熟悉整个电子结构和过程是正确的。现在我必须了解更多信息,稍后再讨论这个问题。

标签: javascript html jquery electron


【解决方案1】:

您混淆了您的main and renderer processes。使用 Electron,所有负责您的 UI 的代码,即附加到在 BrowserWindows 中加载的 HTML 的 JavaScript,在渲染器进程中运行,所有其他代码,例如,负责打开窗口或设置你app 在主进程中运行。

在这个主进程中,你不能使用特定于 DOM 的全局变量,因为主进程是一个纯 Node.js 的东西。你想用 jQuery 做什么,即

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

仍然无法工作,因为document 没有在主进程中定义。此外,主进程的环境与渲染器进程分离(这就是为什么您必须使用 IPC 在它们之间进行通信的原因),因此 $ 未在您的 main.js 中定义,因为您在渲染器 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 架构,因为如果不熟悉可以只需了解此设计即可轻松解决。

【讨论】:

  • 感谢您的快速回复!!我会听取您的建议并了解有关电子的更多信息。你写的这已经很有帮助了,因为我不熟悉你提到的大多数描述我的问题的术语。
  • @mano 首先,不客气。如果这篇文章对您有所帮助,请考虑通过单击灰色复选标记和/或投票将其标记为已接受。
猜你喜欢
  • 1970-01-01
  • 2016-06-04
  • 2020-01-22
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多