【问题标题】:Electron ipc using remote website?电子 ipc 使用远程网站?
【发布时间】:2016-02-05 20:12:29
【问题描述】:

我正在使用远程 url 创建一个electronBrowserWindow,所以我不能真正使用var ipc = require('ipc'); 语法来包含ipc。可以将消息从远程 url 发送到电子主进程吗?如果是这样,我在哪里可以得到它的 javascript 源代码?

或者也许有更好的方法将信息传递给电子主进程?只需要发送登录的用户信息。

【问题讨论】:

  • 为什么不能只使用IPC?该页面可能是从远程 URL 加载的,但其中的 JavaScript 仍由 Electron 执行。
  • @MattHarrison 理想情况下,远程页面将独立于电子应用程序。
  • 听起来您想要一个您的网站和本机应用程序(电子)都可以访问的 API。
  • 是的,但我认为我仍然需要一种方法让网站将登录的用户 ID 传递给电子主进程。然后主进程将能够获取与该用户相关的信息。

标签: javascript node.js ipc electron


【解决方案1】:

很久以前就有人问过这个问题,但我认为这仍然很有用。您可以将 Javascript 注入浏览器窗口的方式是使用预加载延迟,在 Web 首选项中添加选项:

const window = new BrowserWindow({
                    webPreferences:{
                     preload: <path_to>/preload.js
                    }
                   })
// preload.js

const ipcRenderer = require('electron').ipcRenderer;
window.ipcRenderer = ipcRenderer

在你的网页中,你正在加载的外部网址可以直接使用window.ipcRenderer

【讨论】:

    【解决方案2】:

    如果发现将 nodeIntegration 设置为 true 作为 webPreferences 的一部分修复了此问题并允许“要求”ipc 模块并在其上调用发送

    main.js
    
     var authWindow = new BrowserWindow({
            width: 450,
            height: 300,
            show: false,
            parent: mainWindow,
            modal: true,
            webPreferences:{
          nodeIntegration: true
         }
      });
    

    请注意设置此选项的安全隐患,因为您可能正在执行来自未知来源的脚本

    https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content

    【讨论】:

      【解决方案3】:

      我相信我解决了它。使用 angular 所以我做了一个工厂,但是相同的 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());
                  }
              }
      
          };
      
      });
      

      【讨论】:

        猜你喜欢
        • 2021-04-03
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        • 2010-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多