ipcRenderer.on() 函数未收到 mainWindow.webContents.send()

Kod*_*_12 5 javascript node.js electron

在电子 main.js 中,我想将事件从子窗口发送到主窗口。我想做到这一点的方法是从子窗口发送一个事件到主进程,然后主进程发送一个事件到主窗口。

ipcMain.on('submit-form-data', (event, data) => {

    if (data) {
        console.log('send data to main window')
        mainWindow.webContents.send('submitted-form', data)
    }

        childWindow.hide();
    })
Run Code Online (Sandbox Code Playgroud)

childWindow 成功将其表单数据发送到主进程。但是当我希望主进程将该数据发送到主窗口时,该事件没有被拾取。我不知道我可以尝试什么来让它发挥作用。

主窗口中的index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Main Window</title>
  <script>
      var ipcRenderer = nodeRequire("electron").ipcRenderer;

      ipcRenderer.on("submitted-form", function (event, data) {
        alert('received data'); // this never gets called :(
      });
</script>
Run Code Online (Sandbox Code Playgroud)

小智 5

用 包裹你的mainWindow.webContents.send('submitted-form', data);线mainWindow.webContents.on('did-finish-load', ()=>{});。解决了我的问题,希望对你也有帮助。

mainWindow.webContents.on('did-finish-load', ()=>{
  mainWindow.webContents.send('submitted-form', data);
})
Run Code Online (Sandbox Code Playgroud)


snw*_*flk 3

它有效,您需要nodeIntegration在 BrowserWindow 上启用并修复以下内容的导入ipcRenderer

app.js(主进程)

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

let mainWindow

app.on("ready", function() {
    mainWindow = new BrowserWindow({
        width: 500,
        height: 300,
        webPreferences: {
            nodeIntegration: true
        }
    })
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, "index.html"),
        protocol: "file:",
        slashes: true
    }))

    mainWindow.toggleDevTools()

    setTimeout(() => {
        console.log("sending message from main process")
        mainWindow.webContents.send("submitted-form", "hello")
    }, 3000)
})
Run Code Online (Sandbox Code Playgroud)

index.html(渲染器进程)

<!DOCTYPE html>
<html>
<body>
Index with renderer javascript
</body>
<script type="text/javascript">
    const { ipcRenderer } = require("electron")

    ipcRenderer.on("submitted-form", function (event, data) {
        console.log("received data", data)

        alert("received data")
    });
</script>
</html>
Run Code Online (Sandbox Code Playgroud)