2016-02-29 46 views
3

我在本地存儲中有一些數據必須在app.quit()上刪除。但是我從主流程中看不到這樣做。Electron:主要調用渲染器函數

有沒有辦法從main調用renderer函數?我知道var remote = require('remote');,但它似乎只走錯了方向。

回答

9

您可以通過webContents.send將主流程中的消息發送到渲染器進程,如文檔中所示:https://github.com/atom/electron/blob/master/docs/api/web-contents.md#webcontentssendchannel-arg1-arg2-

這裏是你如何從文檔做直:

的主要工序:

// In the main process. 
var window = null; 
app.on('ready', function() { 
    window = new BrowserWindow({width: 800, height: 600}); 
    window.loadURL('file://' + __dirname + '/index.html'); 
    window.webContents.on('did-finish-load', function() { 
    window.webContents.send('ping', 'whoooooooh!'); 
    }); 
}); 

index.html中:

<!-- index.html --> 
<html> 
<body> 
    <script> 
    require('electron').ipcRenderer.on('ping', function(event, message) { 
     console.log(message); // Prints "whoooooooh!" 
    }); 
    </script> 
</body> 
</html> 

值得注意的是異步的。我不確定這是如何影響您的特定解決方案的,但這至少應該讓您回到渲染器流程。

+0

很酷,謝謝。我稍後再檢查一下 –

1

你可以在你的主要過程中使用BrowserWindow.webContents.executeJavaScript像這樣:

// will print "whoooooooh!" in the dev console 
window.webContents.executeJavaScript('console.log("whoooooooh!")'); 

雖然你可能認爲這是一個有點凌亂/骯髒的方式,它的工作原理。而且它不需要在渲染過程中設置任何東西,這大大簡化了我的工作。
如果你只是想調用一個特定的方法,它可能會更快地寫這種方式。