【问题标题】:Electron window.opener full support as in BrowserElectron window.opener 完全支持浏览器
【发布时间】:2017-01-21 07:56:33
【问题描述】:

我正在开发基于 Electron 的多窗口桌面应用程序,我需要与应用程序的其他窗口共享来自主应用程序进程的对象实例。目前在浏览器(Chrome 52.0.2743.116)中,您可以参考 window.opener 来实现这一点。在浏览器中 window.opener (在子窗口中)将为您提供调用 window.opent(myURL) 的 Window 对象的实例。

例如,如果您在window.myData = {}; (Main window) 中设置myData 的相同实例将在(子窗口)中可用,并将通过(window.opener.myData)访问

在 Electron 中,当我通过 (window.opent(myURL)) 打开窗口时,window.opener 被 BrowserWindowProxy(Electron API)替换,它不会暴露调用 (window.open(myURL)) 的相同窗口(Window 对象实例)。 Electron 中是否可以像在浏览器中一样访问 window.opener?

使用 remote.sharedObject (Electron API) 不是一种选择,因为它只序列化/反序列化数据,可用于将数据从一个窗口传递到其他窗口,但不能跨窗口访问相同的对象实例。

【问题讨论】:

    标签: node.js shared-memory electron


    【解决方案1】:

    更正window.opener,并使用facebook(和其他)登录

    您需要使用webPreferences.nativeWindowOpen=true,并为主窗口设置相同的webPreferences.affinity,并打开窗口(挂钩mainWindow.webContents.on('new-window')https://gist.github.com/Gvozd/2cec0c8c510a707854e439fb15c561b0

    【讨论】:

    • Tnx 伙计,你写的听起来很合理 :) 会测试它并给你反馈。
    【解决方案2】:

    我认为您对 remote api 的看法是错误的。来自doc

    远程模块返回的每个对象(包括函数)代表主进程中的一个对象(我们称之为远程对象或远程函数)。

    试试这个:

    'use strict'
    let Electron = require('electron')
    let mainWindow = null
    
    class myObj {
      constructor(d) {
        console.log('constructor ' + d)
        this.d = d
      }
    
      get data() {
        console.log('get ' + this.d)
        return this.d
      }
    
      set data(d) {
        this.d = d
        console.log('set ' + this.d)
      }
    }
    
    global.someObj = new myObj(1)
    
    Electron.app.on('ready', () => {
      mainWindow = new Electron.BrowserWindow()
      mainWindow.loadURL(`file://${__dirname}/index.html`)
      mainWindow.webContents.openDevTools()
      mainWindow.on('closed', () => {
        mainWindow = null
      })
    })
    Electron.app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') {
        Electron.app.quit()
      }
    })
    

    <!DOCTYPE html>
    <html>
      <head>
        <script>
          let obj = require('electron').remote.getGlobal('someObj')
          console.log(obj)
          console.log(obj.data)
          obj.data = 2
          console.log(obj.data)
        </script>
      </head>
      <body></body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 2012-04-10
      • 2019-07-30
      • 2012-02-14
      • 2010-11-24
      相关资源
      最近更新 更多