javascript - 调用主进程的函数

标签 javascript html electron

我试图在单击按钮时从另一个 Javascript 文件调用主进程的函数。代码如下:

ma​​in.js

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

app.on('ready', () => {
let win = new BrowserWindow({width:800,height:600})
win.loadURL(`file://${__dirname}/index.html`)
})

exports.openWindow = () => {
alert("Hello Javatpoint");
}

index.html

<!doc html>
<html>
<head>
<title>
Test 1
</title>
</head>

<body>
<h1>Hello world</h1>
<script src="index.js"></script>
</body>
</html>

index.js

const main = require('electron').remote.require('./main')


var button = document.createElement('button')
button.textContent = 'Open'
button.addEventListener('click',() => {
main.openWindow()
}, false)
document.body.appendChild(button)

当我单击该按钮时,它应该显示一个警报对话框。但它没有显示任何东西。我是 Electron 新手。我想知道它不起作用的原因。请帮忙。

最佳答案

代码有效,函数已导出,唯一的错误是在主进程内,警报函数不存在。您只能查看控制台,您应该会看到错误:

Error Electron

警报功能在主进程(main.js)中不可用,因为这不是渲染器进程。您可以使用 console.log 更改警报,这应该有效:

exports.openWindow = () => {
    // You should see this data on the console that
    // starts electron, not in the JavaScript console of electron !
    console.log("Hello Javatpoint");
};

在此过程中您无法直接访问 DOM 函数。如前所述,要查看图形结果,您可以执行 console.log 以查看启动 Electron 应用程序的控制台上的字符串:

Console Log Electron Main Process

正确的操作方法

如果您想遵循标准,您可以使用ipcMainipcRenderer Electron 数:

ma​​in.js

const {ipcMain} = require('electron');

ipcMain.on('open-window', (event, arg) => {
// prints "ping"
console.log(arg);

event.sender.send('open-window-response', 'pong');
})

index.js

const {ipcRenderer} = require('electron');

ipcRenderer.on('open-window-response', (event, arg) => {
    // prints "pong" in the JS console (chromium)
    console.log(arg);
});

var button = document.createElement('button');

button.textContent = 'Open';

button.addEventListener('click',() => {

     ipcRenderer.send('open-window', 'ping');

}, false);  

document.body.appendChild(button)

关于javascript - 调用主进程的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45657983/

相关文章:

javascript - 保护Processing.js源代码

css - 如何去除div周围的白色边框

electron - 如何在Spectron的新Application()中访问webdriver和chromedriver选项?

javascript - 如何在一个页面上放置多个canvas js动画。 (创建)

javascript - 通过示例了解 javascript 函数作用域

javascript - 将 "click outside of menu to close"jQuery/Javascript 添加到具有 .toggle() 的菜单下拉菜单

node.js - Node writeFileSync 图像编码选项

javascript - 更新后父 View 未在 Electron 中的 <webview> 上设置全局变量

javascript - 为什么我在 vue.js 的 android web-view 中看到这个错误

html - 垂直居中全屏图像