如何从渲染过程的主过程访问对象[Electron] [英] How do I access an object from the main process from a render process [Electron]

查看:94
本文介绍了如何从渲染过程的主过程访问对象[Electron]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图创建一个工具来编辑包含与我的公司业务逻辑相关的对象的文件。我正在使用电子。

I'm trying to create a tool for editing files containing a object that is related to my companies business logic. I'm using electron to do so.

我创建了一个javascript类来表示对象,处理其内部并在其上提供商务功能:

I've created a javascript class which represents the object, handles its internals, and provides buisness functions on it:

class Annotation {
    constructor() {
        this._variables = []
        this._resourceGenerators = []
    }

    get variables() {
        return this._variables
    }

    get resourceGenerators() {
        return this._resourceGenerators
    }

    save(path) {
        ...
    }

    static load(path) {
        ...
    }
};

module.exports = Annotation;

我在主进程中创建了对象,并且有一个事件处理程序可让渲染进程访问它:

I create the object in my main process, and I have an event handler which gives render processes access to it:

const {ipcMain} = require('electron')
const Annotation = require('./annotation.js');

... Do electron window stuff here ...

var annotation = new Annotation()

ipcMain.on('getAnnotation', (event, path) => {

    event.returnValue = annotation
})

我刚刚发现,通过ipcMain.sendSync发送对象使用JSON.stringify传递注释,这意味着它会松散其吸气剂/功能。

I've just found out that sending an object through ipcMain.sendSync uses JSON.stringify to pass the annotation, meaning it looses the getters/functions on it.

我对网络/电子开发还很陌生;处理此问题的正确方法是什么?以前,我在main中使用处理程序来处理渲染过程所需的大多数功能,但是main开始变得肿,因此我试图对其进行某种程度的重构。

I'm fairly new to web/electron development; what is the proper way of handling this? Previously I had handlers in main for dealing with most of the functions that the render processes needed, but main started to become very bloated, so I'm trying to refactor it somewhat.

推荐答案

TL; DR:在接收方重建对象。

说明:Electron的主要架构设计基于多进程,将主体(node.js)和每个渲染器分开(铬)工艺,并允许通过IPC机制在工艺之间进行通信。而且由于多种原因(效率,性能,安全性等),Electron的OOTO IPC仅允许发送/接收可序列化的POJO。接收者获得这些数据后,您可能需要从那里重建所需的对象。

Description: Electron's main architectural design is based on multi-process, separating main (node.js) and each renderer (chromium) processes and allow to communicate between processes via IPC mechanism. And due to several reason (efficiency, performance, security, etcs) Electron's OOTO IPC only allows serializable POJO to be sent / received. Once receiver have those data, you may need reconstruct desired object from there.

如果您打算访问是要共享像真实单身人士这样的引用,则不可用。

If your intention around access is to share references like true singleton, that's not available.

这篇关于如何从渲染过程的主过程访问对象[Electron]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆