电子:有没有办法通过ipc访问/修改主进程数组

时间:2018-05-17 07:46:23

标签: javascript ecmascript-6 electron

一般情况下,通过电子ipc传递的数组被复制。

// main process
global['test'] = []
// renderer process
console.log(remote.getGlobal('test')) // []
remote.getGlobal('test').push('1')
console.log(remote.getGlobal('test')) // expected: ['1'], actual: []

但修改对象会很好用。

// main process
global['test'] = {a: 1}
// renderer process
console.log(remote.getGlobal('test')) // {}
remote.getGlobal('test').a += 1
console.log(remote.getGlobal('test')) // expected/actual: {a: 2}

为了能够在渲染器进程中直接修改主进程中的数组,我尝试传递一个在主进程中包装数组的代理:

// Main Process Code
const real = []
global['proxy'] = new Proxy({}, {
  get: (_, property) => Reflect.get(real, property),
  set: (_, property, value, receiver) => Reflect.set(real, property, value, receiver),
  deleteProperty: (_, property) => Reflect.deleteProperty(real, property),
  enumerate: (_) => Array.from(Reflect.enumerate(real)),
  ownKeys: (_) => Reflect.ownKeys(real),
  has: (_, property) => Reflect.has(real, property),
  defineProperty: (_, property, descriptor) => Reflect.defineProperty(real, property, descriptor),
  getOwnPropertyDescriptor: (target, property) => {
    let descriptor = Object.getOwnPropertyDescriptor(real, property)
    if (descriptor) {
      descriptor.value = real[property]
      Reflect.defineProperty(target, property, descriptor)
    }
    return descriptor
  }
})

// Renderer Process Code
const proxy = remote.getGlobal('proxy')

proxy.push(1) // error thrown: Uncaught TypeError: proxy.push is not a function
console.log(proxy.join(','))

正如代码注释中所表达的那样,似乎存在使用代理传递值的问题。在这种情况下,还有其他有效和实用的方法来达到我的目的吗?

1 个答案:

答案 0 :(得分:1)

这应该有效。第一个主要过程:

//global array
global.test = {
 myarr: [3]
};

//...electron setup: window etc...

setTimeout(function() {
 console.log(global.test); //now shows 3 and 6
},5000);

在渲染器中(例如index.html脚本):

var remote = require('electron').remote;

var _old = remote.getGlobal('test').myarr;
_old.push(6);

remote.getGlobal('test').myarr = _old; //update global with altered array

console.log(remote.getGlobal('test').myarr); //now shows 3 and 6