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

时间:2019-06-17 02:39:42

标签: javascript node.js electron

在电子main.js中,我想将事件从子窗口发送到mainWindow。我认为这样做的方法是将事件从childWindow发送到主进程,然后主进程将事件发送到mainWindow。

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

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

        childWindow.hide();
    })

childWindow成功将其表单数据发送到主进程。但是,当我希望主进程将数据发送到mainWindow时,该事件就不会被接收。我不知道如何才能使它正常工作。

index.html在mainWindow中

<!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>

2 个答案:

答案 0 :(得分:2)

usort($consts, function($a, $b) { return strlen($b) <=> strlen($a); }); 包裹您的 mainWindow.webContents.send('submitted-form', data); 行。解决了我的问题,希望对你也有帮助。

mainWindow.webContents.on('did-finish-load', ()=>{});

答案 1 :(得分:0)

它有效,您需要在BrowserWindow上启用nodeIntegration并修复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)
})

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>