gpt4 book ai didi

javascript - 如何从渲染器进程调用 Electron API 方法?

转载 作者:行者123 更新时间:2023-11-30 11:50:03 25 4
gpt4 key购买 nike

我一直在尝试 http://electron.atom.io一阵子。我关注了http://electron.atom.io/docs/tutorial/quick-start/并取得了相对成功,我设法使用 Bootstrap 和 Jquery 制作了一个“应用程序”。

但是现在,我尝试使用 Electron API 方法但没有成功。

我创建了一个浏览器窗口,并在该窗口中添加了一个新的 JS 文件。在该文件中,我试图在此处调用 printToPDF 方法:http://electron.atom.io/docs/api/web-contents/#contentsprinttopdfoptions-callback

它只是不起作用,控制台记录以下内容:

未捕获的 ReferenceError:未定义 mainWindow

代码如下:

主要.js

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(`file://${__dirname}/index.html`)
mainWindow.webContents.openDevTools()

mainWindow.on('closed', function () {
mainWindow = null
})
}

app.on('ready', createWindow)

app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">
</head>
<body>
</body>

<script>window.$ = window.jQuery = require('jquery');</script>
<script type="text/javascript" src="./js/bootstrap.min.js"></script>
<script>
require('./app.js');
</script>
</html>

应用程序.js

$(function() {
mainWindow.webContents.printToPDF();
});

最佳答案

看看 ipc 模块,ipcMainipcRenderer . ipc 模块允许您在主进程和渲染进程之间发送和接收同步和异步消息。

这里是来自 ELECTRON API DEMOS 的打印到 PDF 的例子应用程序。

渲染器进程

const ipc = require('electron').ipcRenderer

const printPDFBtn = document.getElementById('print-pdf')

printPDFBtn.addEventListener('click', function (event) {
ipc.send('print-to-pdf')
})

ipc.on('wrote-pdf', function (event, path) {
const message = `Wrote PDF to: ${path}`
document.getElementById('pdf-path').innerHTML = message
})

主进程

const fs = require('fs')
const os = require('os')
const path = require('path')
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
const shell = electron.shell

ipc.on('print-to-pdf', function (event) {
const pdfPath = path.join(os.tmpdir(), 'print.pdf')
const win = BrowserWindow.fromWebContents(event.sender)
// Use default printing options
win.webContents.printToPDF({}, function (error, data) {
if (error) throw error
fs.writeFile(pdfPath, data, function (error) {
if (error) {
throw error
}
shell.openExternal('file://' + pdfPath)
event.sender.send('wrote-pdf', pdfPath)
})
})
})

关于javascript - 如何从渲染器进程调用 Electron API 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39746261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com