通常,复制通过 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(','))
如代码注释中所示,似乎存在代理传递值的问题。在这种情况下,还有其他有效且实用的方法可以实现我的目的吗?
最佳答案
这应该工作。第一个主要流程:
//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