在Electron中使用ipc从渲染器设置全局变量 [英] Using ipc in Electron to set global variable from renderer

查看:2048
本文介绍了在Electron中使用ipc从渲染器设置全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

renderer.js

renderer.js

ipcRenderer.sendSync('setGlobal', 'globalVarName').varInner.varInner2 = 'result';

main.js

global.globalVarName = {
  varInner: {
    varInner2: ''
  },
  iWontChange: 'hi'
};

ipcMain.on('setGlobal', (event, arg) => {
  console.log(arg) // should print "result"
  // what goes here?
})

console.log(varInner2) // should print "result"

是否可能这样,即以这种方式设置 globalVarName varInner2 ?其次,是否有一种优化方法,这样我们就不必为每个全局变量重写该过程了(即使用动态变量名进行此操作的某种方法)?

Is something like this possible, namely setting the varInner2 of globalVarName in this manner? Secondly, is there a way to optimize this so we wouldn't have to rewrite this process for every global variable (i.e. some way to do this with dynamic variable names)?

我很感谢任何想法或解决方案,如果这是一个常识性问题,对不起。

I appreciate any ideas or solutions, sorry if this is a common sense question.

推荐答案

使用IPC设置全局值。



使用 getGlobal 效果很好只对读取全局变量的值感兴趣。但是,我发现尝试使用 getGlobal 分配或更改其值是有问题的。

Use IPC to Set the Global's Value.

Using getGlobal works great when you're only interested in reading the value of the global variable. However, I found that trying to assign or change its value using getGlobal to be problematic.

我发现Main流程中的全局变量没有实际更改。具体来说,当刷新开发中的Electron窗口时,全局变量将重新设置为其原始值。这使恢复开发状态成为一个问题。

In my case, I found that the global variable on the Main process didn't actual change. Specifically, when refreshing the Electron window in development, the global variables were set back to their original value. This made restoring state in development an issue.

不确定这是否也在生产中发生,但是我想会发生,因此,将依赖于全局变量最新值的新流程拆分为

Not sure if this also was occurring in production, but I imagine it would, so spinning up new processes that relied on up-to-date values of global variables would be problematic.

相反,我最终使用了更详细的方法 ipcMain ipcRenderer

Instead, I ended up using the more verbose method of ipcMain and ipcRenderer.

main.js

const { ipcMain } = require( "electron" );

ipcMain.on( "setMyGlobalVariable", ( event, myGlobalVariableValue ) => {
  global.myGlobalVariable = myGlobalVariableValue;
} );

renderer.js

const { ipcRenderer, remote } = require( "electron" );

// Set MyGlobalVariable.
ipcRenderer.send( "setMyGlobalVariable", "Hi There!" );

// Read MyGlobalVariable.
remote.getGlobal( "MyGlobalVariable" ); // => "Hi There!"

这篇关于在Electron中使用ipc从渲染器设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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