상세 컨텐츠

본문 제목

electron ipcRenderer -> ipcMain

code/electron.js

by goldtagworks 2024. 7. 10. 21:37

본문

반응형
const { ipcRenderer } = window as any;

/**
 * 일렉트론에는 메인쪽에서 요청한 결과를 렌더러에서 처리하고 다시 돌려줄 API 가 존재하지 않는다.
 * 예를들어 메인에서 렌더러에 컨펌 메세지를 띄우고 사용자가 확인을 했는지 취소를 했는지 다시 메인에서 응답을 받아볼 방법이 없다.
 * 이러한 처리를 하기위한 헬퍼 함수이다.
 */
export const ipcHelper = {
    handle: (channel: string, callback: (callFuncName: string, params: any) => any) => {
        try {
            const asyncCallback = async (event: any, args: { asyncKey: string; callFuncName: string; params: any }) => {
                // UI 에서 처리한 후
                const result = await callback(args.callFuncName, args.params);
                // 메인에 결과를 보낸다. 응답받을 채널은 중복나지 않도록 asyncKey 로 응답한다.
                ipcRenderer.send(`async:${channel}:${args.asyncKey}`, result);
            };

            // 이벤트를 받으면 asyncCallback 를 호출한다.
            ipcRenderer.on(channel, asyncCallback);
            return () => ipcRenderer.removeListener(channel, asyncCallback);
        } catch (error) {
            // console.log(error);
        }
    },

    invoke: async (channel: string, callFuncName: string, params: any): Promise<any> => {
        try {
            return ipcRenderer.invoke(channel, callFuncName, params);
        } catch (error) {
            // console.log(error);
        }
    },

    on: (channel: string, callback: (event: any, args: { callFuncName: string; params: any }) => any) => {
        try {
            ipcRenderer.on(channel, callback);
        } catch (error) {
            // console.log(error);
        }
    },

    removeAllListeners: (channel: string) => {
        try {
            ipcRenderer.removeAllListeners(channel);
        } catch (error) {
            // console.log(error);
        }
    }
};
반응형

관련글 더보기