javascript - 从其他文件使用 Electron 远程

标签 javascript node.js electron

我有一个文件,其中包含一个打开文件打开对话框的函数。我想从应用程序的菜单中调用该功能。但是当我使用 require使用文件中的函数我得到一个错误。
代码:
主.js:

const { app, BrowserWindow, Menu } = require('electron');
const url = require('url');
const path = require('path');
const { openFile } = require('./index.js');

let win;

function createWindow() {
    win = new BrowserWindow({
        width: 800,
        height: 600,
        icon: __dirname + 'src/styles/media/icon.ico',
        webPreferences: {
            nodeIntegration: true,
            enableRemoteModule: true,
        },
    });
    win.loadURL(
        url.format({
            pathname: path.join(__dirname, 'src/index.html'),
            protocol: 'file:',
            slashes: true,
        })
    );
    var menu = Menu.buildFromTemplate([
        {
            label: 'File',
            submenu: [
                {
                    label: 'Open File',
                    click() {
                        openFile();
                    },
                    accelerator: 'CmdOrCtrl+O',
                }
            ]
        }]);
    Menu.setApplicationMenu(menu);
}

app.on('ready', createWindow);
index.js:
const { dialog } = require('electron').remote;

function openFile() {
    dialog.showOpenDialog({
        title: 'Open File',
        properties: ['openFile'],
    });
}

module.exports = {
    openFile,
};
索引.html:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="styles/style.css" />
        <title>Stonecutter</title>
    </head>
    <body>
        <script src="./index.js"></script>
    </body>
</html>
错误:
error
当我做同样的事情但没有 required代码工作正常:
// index.js
// --------
// This code works
function openFile() {
    console.log('Open file');
}

module.exports = {
    openFile,
};

// Main.js is the same

最佳答案

您在主进程中使用 Remote 。这就是导致问题的原因。远程是您在渲染器进程中使用的(BrowserView 所需的脚本)。所以你需要为 main 和 renderer 进程编写两个不同的 openFile 函数。
所以当你需要 index.js来自 main.js这就是导致错误的原因。您需要确定您在主进程或渲染器中的位置。观看 open-file.js下面看看怎么做。
总而言之,它应该看起来像这样:
main.js

const { app, BrowserWindow, Menu } = require('electron');
const url = require('url');
const path = require('path');
const {openFile} = require('./open-file')

let win;

function createWindow() {
    win = new BrowserWindow({
        width: 800,
        height: 600,
        icon: __dirname + 'src/styles/media/icon.ico',
        webPreferences: {
            nodeIntegration: true,
            enableRemoteModule: true,
        },
    });
    win.loadURL(
        url.format({
            pathname: path.join(__dirname, 'index.html'),
            protocol: 'file:',
            slashes: true,
        })
    );

  }

app.on('ready', () => {
  createWindow()
  var menu = Menu.buildFromTemplate([
  {
      label: 'File',
      submenu: [
          {
              label: 'Open File',
              click() {
                  openFile();
              },
              accelerator: 'CmdOrCtrl+O',
          }
      ]
  }]);
  Menu.setApplicationMenu(menu);
})

index.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="styles/style.css" />
        <title>Stonecutter</title>
    </head>
    <body>
      <button id="open-file">Open file</button>
      <script>
        const {openFile} = require('./open-file.js')

        document.querySelector('#open-file').addEventListener('click', () => openFile())
      </script>
    </body>
</html>

open-file.js
const electron = require('electron');

// electron.remote for Renderer Process and electron for Main Process
const {dialog} = (electron.remote || electron)

function openFile() {
    dialog.showOpenDialog({
        title: 'Open File',
        properties: ['openFile'],
    });
}

module.exports = {
    openFile,
};


此示例按您的预期工作。文件 open-file.js是您在 index.js 中所拥有的.
这是因为 Electron 在不同的进程中运行它的部分:第一个是 Main process .这是您在运行 electron main.js 时得到的结果.第二个是Renderer process在单独的操作系统进程中运行。您可以在此处调用 win.loadURL()它的 API 和库集略有不同。

关于javascript - 从其他文件使用 Electron 远程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65295037/

相关文章:

javascript - 如何链接具有 namespace 的方法?

javascript - 在来自不同来源的 angularjs select 指令中设置所选项目

node.js - 使用带有 webpack 的 google-api-nodejs-client 进行 grunt 构建时出错

node.js - Nodejs(同步)找不到纤程二进制文件

javascript - 给定这个脚本,我怎样才能把子菜单放在主菜单的左边?

javascript - 如何让 Firefox 自动在 JQuery UI 对话框中填写保存的密码?

javascript - 如何使用nodemailer发送pdf附件?

node.js - NodeJS - 如何控制 Promise 的执行流程?

javascript - 需要 ('electron' ).app 未定义 - 如何解决此问题

reactjs - 无法为 Electron 构建 .exe