Skip to content

useIpcRenderer

Category
Export Size
387 B
Package
@reause/electron
Last Changed
5 days ago

Provides ipcRenderer and all of its APIs.

Demo

Usage

tsx
import { 
useIpcRenderer
} from '@reause/electron'
// enable nodeIntegration if you don't provide ipcRenderer explicitly // see: https://www.electronjs.org/docs/api/webview-tag#nodeintegration const
ipcRenderer
=
useIpcRenderer
()
// Promise result (upstream returned a ShallowRef) const
result
= await
ipcRenderer
.
invoke
<string>('custom-channel', 'some data')
// listeners registered through `on` are removed automatically on unmount
ipcRenderer
.
on
('custom-event', (
event
, ...
args
) => {
console
.
log
(
args
)
})

Available Methods

MethodDescription
on(channel, listener)Listen to channel. Auto-removes listener on unmount.
once(channel, listener)Listen to channel once
removeListener(channel, listener)Remove specific listener
removeAllListeners(channel)Remove all listeners for channel
send(channel, ...args)Send async message to main process
invoke(channel, ...args)Send message and get the response as Promise<T>
sendSync(channel, ...args)Send sync message and get the response as T
postMessage(channel, message, transfer?)Send message with transferable objects
sendTo(webContentsId, channel, ...args)Send to specific webContents
sendToHost(channel, ...args)Send to webview host

With Custom IpcRenderer

If nodeIntegration is disabled, you can pass the ipcRenderer instance explicitly:

tsx
import { 
useIpcRenderer
} from '@reause/electron'
import {
ipcRenderer
} from 'electron'
const
ipc
=
useIpcRenderer
(
ipcRenderer
)

Type Declarations

ts
export interface UseIpcRendererReturn {
    on: (channel: string, listener: IpcRendererListener) => IpcRenderer;
    once: (channel: string, listener: (event: IpcRendererEvent, ...args: any[]) => void) => IpcRenderer;
    removeListener: (channel: string, listener: (...args: any[]) => void) => IpcRenderer;
    removeAllListeners: (channel: string) => IpcRenderer;
    send: (channel: string, ...args: any[]) => void;
    invoke: <T>(channel: string, ...args: any[]) => Promise<T>;
    sendSync: <T>(channel: string, ...args: any[]) => T;
    postMessage: (channel: string, message: any, transfer?: MessagePort[]) => void;
    sendTo: (webContentsId: number, channel: string, ...args: any[]) => void;
    sendToHost: (channel: string, ...args: any[]) => void;
}

export type IpcRendererListener = (event: IpcRendererEvent, ...args: any[]) => void

export function useIpcRenderer(ipcRenderer?: IpcRenderer): UseIpcRendererReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
e08b8 - fix(electron): resolve useIpcRenderer audit findings (#808)
9a6d8 - feat(electron): add useIpcRenderer, useIpcRendererInvoke, useIpcRendererOn (#148, #149, #150)

Released under the MIT License. v0.1.8