【问题标题】:Electron.js: Requiring a remote module doesn't let the script workElectron.js:需要远程模块不会让脚本工作
【发布时间】:2021-11-24 01:12:07
【问题描述】:

我想使用自定义按钮为我的无框窗口添加自定义标题。

我有两个脚本文件 - index.js,在 Electron 启动时自动运行,app.js,在 index.html 中添加了 <script src> 标签。

有一个问题 - require() 不让脚本工作 - 如果我需要任何模块,则不会运行任何行,不管它是什么。

index.html:

<head>
    ...
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="app.js"></script>
    ...
</head>

index.js

const {app, BrowserWindow} = require('electron')
const path = require('path')
const sass = require('sass')
const fs = require('fs')

// Creates a main window
function createWindow () {
    renderStylesheets()
    let mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        resizable: true,
        transparent: true,
        frame: false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
    mainWindow.loadFile('index.html').then(() => {})
}

...

app.js

alert("This alert won't show.")

// If I remove these lines, alerts and jQuery's "$(callback)" will run, but
// button actions won't work :(
const { BrowserWindow, app } = require('electron').remote;
let window = BrowserWindow.getFocusedWindow();

alert("This alert won't show and the $(() => {}) won't run too.")

...

【问题讨论】:

    标签: javascript html node.js electron


    【解决方案1】:

    问题出在哪里?如果它在index.html 中,那么问题出在显示的第 4 行。确保您引用了正确的网站并且您引用了正确的数据。

    如果问题出在index.js 中,那么问题可能出在所示内容的第 8 行,因为您需要确保在第 8 行之前提到或声明了变量“app”。

    这是我立即看到的唯一可能导致此问题的两件事。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      问题是app.js 和任何其他脚本都没有require 函数。为了在主脚本之外添加对 Node.js 函数的访问,我在窗口初始化程序中设置了 nodeIntegration: truecontextIsolation: false

      mainWindow = new BrowserWindow({
              width: 900,
              height: 600,
              resizable: true,
              transparent: true,
              show: true,
              frame: false,
              center: true,
              webPreferences: {
                  preload: path.join(__dirname, 'preload.js'),
                  nodeIntegration: true,    // <- This one
                  contextIsolation: false,  // <- And this one
              }
          })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 2017-04-30
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多