티스토리 뷰

반응형

Electron은 메인 프로세스와 렌더 프로세스가 존재합니다. 각 프로세스는 독립적이기 때문에 서로간 직접 접근할 수 없고 통신이라는 간접적 방법으로 접근해야 합니다.

 

통신에는 IPC(inter-process)와 remote 두 가지의 방식이 있는데, IPC는 메세지로 통신하지만, remote는 이를 추상화하여 더 쉽게 접근과 사용을 가능하게 합니다.

 

@electron/remote is a replacement for the built-in remote module in Electron, which is deprecated and will eventually be removed.

그리고 remote 모듈은 Electron에 기본으로 포함된 기능이였으나 곧 제거가 될거라고 합니다(글 작성 기준으로 Electron ^16.0.5에서는 이미 제거됨). 그래서 npm 등을 통해 별도 Package 설치가 필요합니다.

 

이 글은 ERB 환경 기준으로 작성되었습니다. ERB는 아래 글을 참고해주세요.

https://bundw.tistory.com/78

 

Electron(일렉트론) React(리액트) ERB로 데스크톱 앱 만들기

https://www.electronjs.org/ Electron | Build cross-platform desktop apps with JavaScript, HTML, and CSS. Build cross-platform desktop apps with JavaScript, HTML, and CSS. www.electronjs.org 웹 프로..

bundw.tistory.com

 

준비

@electron/remote를 설치합니다.

$ npm install --save @electron/remote

 

메인 프로세스에 해당되는 main.ts파일에서 require('@electron/remote/main').initialize() 내용을 추가합니다.

const createWindow = async () => {
  if (isDevelopment) {
    await installExtensions();
  }
  ...
  
  require('@electron/remote/main').initialize();
  
  ...

 

사용

값이나 함수 저장은 global에 접근해서 사용합니다. Javascript경우, global.myval = 123; 형태로 사용 가능하지만, Typescript인 경우 오류를 발생시키므로 global을 재정의해서 사용합니다.

// Typescript
let gt = global as typeof globalThis & {
  myval: string;
  myfunc: Function;
};

gt.myval = "Hello World!";
gt.myfunc = function() {
  console.log("Hello World!");
};

 

저장된 값이나 함수는 다음과 같이 접근할 수 있습니다.

const remote = require('@electron/remote');

let val = remote.getGlobal('myval');
remote.getGlobal('myfunc')(); // call function

 

문제 해결

@electron/remote is disabled for this WebContents. Call require("@electron/remote/main").enable(webContents) to enable it.오류가 발생했을 경우, main.ts파일에서 require('@electron/remote/main').initialize() 내용아래에 require("@electron/remote/main").enable(mainWindow.webContents)를 추가합니다.

const createWindow = async () => {
  if (isDevelopment) {
    await installExtensions();
  }
  ...
  mainWindow.loadURL(resolveHtmlPath('index.html'));
  ...

  require('@electron/remote/main').initialize();
  require("@electron/remote/main").enable(mainWindow.webContents);
  
  ...
반응형
반응형