未调用电子渲染器

Electron renderer not invoked

我正在学习 electron,学习了 electron-quick-start 并按照以下教程对 index.html、main.js 和 renderer.js 进行了某些修改 https://blog.logrocket.com/handling-interprocess-communications-in-electron-applications-like-a-pro/

index.html

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  <title>Electron-Process-Comm</title>
  <link rel="stylesheet" href="style.css">
  <meta charset="UTF-8">
  <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
  <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
  <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
</head>
<body>
<h2 id="mainWindowTitle">I am the main window</h2>
<button id="sendSyncMsgBtn">Ping Main Process</button>
<p id="syncReply">Chilling for response</p>

<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>

main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
const ipcMain = require('electron').ipcMain

console.log('Hello')

ipcMain.on('sync-message', (event, arg) => {
  console.log('IPCMain')
  event.returnValue = 'Message Recieved!'
})

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

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

renderer.js

const electron = require('electron')
const ipc = electron.ipcRenderer

const syncMsgBtn = document.querySelector('#sendSyncMsgBtn')

console.log('Hello renderer')

syncMsgBtn.addEventListener('click', () => {
  console.log('Renderer')
  const reply = ipc.sendSync('sync-message', 'Sent from main Window')
  const message = `Synchronous message reply: ${reply}`
  document.querySelector('#syncReply').innerHTML = message
})

const asyncMsgBtn = document.querySelector('#sendAsyncMsgBtn')

asyncMsgBtn.addEventListener('click', () => {
  ipc.send('async-message', 'Async message baby')

})

现在,虽然 renderer.js 包含在 index.html 中,但它永远不会被调用。控制台日志不出现,按钮单击不响应。有人可以告诉我我做错了什么吗?

代码看起来不错,应该在 运行 时执行。您可能看错了控制台?日志语句应该出现在渲染器的控制台中 window。要打开开发人员工具,您可以按 Cmd + Opt + I (macOS) 和 Ctrl + Shift + I (Windows).

您可以在 their documentation and the Developer Tools in Chrome's documentation 中找到有关调试 Electron 应用程序的更多信息。