Bil*_*ton 6 javascript ipc node.js electron
我正在使用远程 url创建一个电子 BrowserWindow,所以我不能真正使用var ipc = require('ipc');语法来包含 ipc。可以将消息从远程 url 发送到电子主进程吗?如果是这样,我在哪里可以获得它的 javascript 源代码?
或者也许有更好的方法将信息传递给电子主进程?只需要发送登录的用户信息。
小智 6
很久以前就有人问过这个问题,但我认为这仍然有用。您可以将 Javascript 注入浏览器窗口的方法是使用预加载延迟,在网络首选项中,添加选项:
const window = new BrowserWindow({
webPreferences:{
preload: <path_to>/preload.js
}
})
Run Code Online (Sandbox Code Playgroud)
// preload.js
const ipcRenderer = require('electron').ipcRenderer;
window.ipcRenderer = ipcRenderer
Run Code Online (Sandbox Code Playgroud)
在您正在加载的外部网址的网页中,您可以直接使用window.ipcRenderer.
我相信我解决了它。使用角度所以我创建了一个工厂,但是相同的 try/catch 方法应该适用于任何东西。如果从电子运行,则发送 ipc 消息,否则它们将被忽略。
angular.module('IpcFactory', [])
.factory('IpcFactory', function(){
var ipcAvailable;
try{
var ipc = require('ipc');
ipcAvailable = true;
}
catch(e){
ipcAvailable = false;
}
return {
ipcAvailable: ipcAvailable,
send: function(event, message){
var self = this;
if(self.ipcAvailable){
ipc.send(event, message);
}
},
on: function(event, fn){
var self = this;
if(self.ipcAvailable){
ipc.on(event, fn());
}
}
};
});
Run Code Online (Sandbox Code Playgroud)