electron#IpcRenderer TypeScript Examples
The following examples show how to use
electron#IpcRenderer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: storageProvider-electron.ts From celo-web-wallet with MIT License | 6 votes |
function getAppCwdPath(filePath: string) {
if (!filePath) throw new Error('Invalid storage path')
if (!defaultCwd) {
const metadata = ipcRenderer.sendSync('get-app-metadata')
if (metadata && metadata.defaultCwd) {
defaultCwd = metadata.defaultCwd
} else {
throw new Error('Failed to retrieve app metadata from IPC')
}
}
return path.join(defaultCwd, filePath)
}
Example #2
Source File: preloadBindings.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
preloadBindings = function (ipcRenderer: IpcRenderer): {
onLanguageChange: (callback: (language: { lng: string }) => unknown) => void;
onReceive: (channel: I18NChannels, callback: (readWriteFileArgs: IReadWriteFileRequest) => void) => void;
send: (channel: I18NChannels, readWriteFileArgs: IReadWriteFileRequest) => Promise<void>;
} {
return {
send: async (channel: I18NChannels, readWriteFileArgs: IReadWriteFileRequest): Promise<void> => {
const validChannels = [I18NChannels.readFileRequest, I18NChannels.writeFileRequest];
if (validChannels.includes(channel)) {
await ipcRenderer.invoke(channel, readWriteFileArgs);
}
},
onReceive: (channel: I18NChannels, callback: (readWriteFileArgs: IReadWriteFileRequest) => void) => {
const validChannels = [I18NChannels.readFileResponse, I18NChannels.writeFileResponse];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes "sender"
ipcRenderer.on(channel, (_event: IpcRendererEvent, arguments_: IReadWriteFileRequest) => callback(arguments_));
}
},
onLanguageChange: (callback: (language: { lng: string }) => unknown) => {
// Deliberately strip event as it includes "sender"
ipcRenderer.on(I18NChannels.changeLanguageRequest, (_event: IpcRendererEvent, language: { lng: string }) => {
callback(language);
});
},
};
}
Example #3
Source File: events.ts From Protoman with MIT License | 6 votes |
export function setupListeners(ipcRenderer: IpcRenderer): void {
ipcRenderer.on(ipcChannels.LOAD_MOST_RECENT, (event, args) => {
console.log('Loaded most recent state ', args);
if (args[0] !== undefined) {
const store = makeStore(args[0]);
setupListenersWithStore(ipcRenderer, store);
initializeApp(store);
}
});
ipcRenderer.on(ipcChannels.MAIN_ERROR, (event, args) => {
console.log('Error from the main process: ', args[0].message);
});
ipcRenderer.on(ipcChannels.EXPORT_CANCELLED, () => {
message.warn('Export cancelled');
});
ipcRenderer.on(ipcChannels.EXPORT_SUCCESS, () => {
message.success('Export success!');
});
ipcRenderer.on(ipcChannels.EXPORT_ERROR, (event, [e]) => {
message.error(`Export error: ${JSON.stringify(e, null, 2)}`, 5);
});
ipcRenderer.on(ipcChannels.IMPORT_CANCELLED, () => {
message.warn('Import cancelled');
});
ipcRenderer.on(ipcChannels.IMPORT_ERROR, (event, [e]) => {
message.error(`Import error: ${JSON.stringify(e, null, 2)}`, 5);
});
}
Example #4
Source File: index.ts From deskreen with GNU Affero General Public License v3.0 | 6 votes |
async setDisplaySizeRetreivedFromMainProcess() {
const size: DisplaySize | 'undefined' = await ipcRenderer.invoke(
'get-display-size-by-display-id',
this.displayID
);
if (size !== 'undefined') {
this.sourceDisplaySize = size;
}
}
Example #5
Source File: Menu.tsx From CrewLink with GNU General Public License v3.0 | 6 votes |
Menu: React.FC<MenuProps> = function ({ error }: MenuProps) {
const classes = useStyles();
return (
<div className={classes.root}>
<div className={classes.menu}>
{error ? (
<div className={classes.error}>
<Typography align="center" variant="h6" color="error">
ERROR
</Typography>
<Typography align="center" style={{ whiteSpace: 'pre-wrap' }}>
{error}
</Typography>
<SupportLink />
</div>
) : (
<>
<span className={classes.waiting}>Waiting for Among Us</span>
<CircularProgress color="primary" size={40} />
<button
className={classes.button}
onClick={() => {
ipcRenderer.send(IpcMessages.OPEN_AMONG_US_GAME);
}}
>
Open Game
</button>
</>
)}
<Footer />
</div>
</div>
);
}
Example #6
Source File: BottomButtons.tsx From SeeQR with MIT License | 6 votes |
BottomButtons = ({ selectedView, setSelectedView, setSelectedDb, selectedDb}: ViewSelectorProps) => (
<ViewBtnGroup variant="contained" fullWidth>
<ViewButton
onClick={() => {
setSelectedView('newSchemaView');
setSelectedDb('');
ipcRenderer
.invoke('select-db', '')
.catch(() =>
sendFeedback({
type: 'error',
message: `Database connection error`
})
)
}}
$isSelected={
selectedView === 'newSchemaView' || selectedView === 'compareView'
}
>
Create New Database
</ViewButton>
</ViewBtnGroup>
)
Example #7
Source File: index.tsx From Aragorn with MIT License | 6 votes |
About = () => {
function handleUpdate() {
ipcRenderer.send('check-update', true);
}
return (
<div className="info-wrapper">
<header>
<span>关于</span>
<Divider />
</header>
<main>
<h3>Aragorn</h3>
<a
style={{ margin: 10 }}
onClick={() => {
shell.openExternal(AppUrl);
}}
>
{AppUrl}
</a>
<p className="desc">v{remote.app.getVersion()}</p>
<Button type="primary" onClick={handleUpdate}>
检查更新
</Button>
</main>
</div>
);
}
Example #8
Source File: App.tsx From nautilus with MIT License | 6 votes |
componentDidMount() {
if (ipcRenderer) {
ipcRenderer.on('file-open-error-within-electron', (event, arg) => {
this.handleFileOpenError(arg);
});
ipcRenderer.on('file-opened-within-electron', (event, arg) => {
this.convertAndStoreYamlJSON(arg);
});
}
const stateJSON = localStorage.getItem('state');
if (stateJSON) {
const stateJS = JSON.parse(stateJSON);
// set d3 state
window.d3State = setD3State(stateJS.services);
this.setState(Object.assign(initialState, stateJS));
}
}
Example #9
Source File: store.ts From mysterium-vpn-desktop with MIT License | 6 votes |
constructor(history: History) {
makeObservable(this, {
os: observable,
isWindows: computed,
isMacOS: computed,
isLinux: computed,
})
this.navigation = new NavigationStore(this, history)
this.daemon = new DaemonStore(this)
this.config = new ConfigStore(this)
this.filters = new Filters(this)
this.identity = new IdentityStore(this)
this.onboarding = new OnboardingStore(this)
this.proposals = new ProposalStore(this)
this.connection = new ConnectionStore(this)
this.payment = new PaymentStore(this)
this.feedback = new FeedbackStore(this)
this.referral = new ReferralStore(this)
// Setup cross-store reactions after all injections.
this.daemon.setupReactions()
this.filters.setupReactions()
this.identity.setupReactions()
this.proposals.setupReactions()
this.payment.setupReactions()
this.connection.setupReactions()
this.setupReactions()
ipcRenderer.invoke(MainIpcListenChannels.GetOS).then((os) => {
runInAction(() => {
this.os = os
})
})
}
Example #10
Source File: walletService.ts From IOTA-2.0-DevNet-wallet with MIT License | 6 votes |
/**
* Create a new instance of WalletService.
*/
constructor() {
this._jsonStorageService = ServiceFactory.get<IJsonStorageService>("json-storage");
this._subscribers = {};
this._reusableAddresses = false;
this._done = true;
ipcRenderer.on("to-renderer", async (event, aManaPledge, cManaPledge, addrress, nonce) => {
// console.log("Renderer: received ", aManaPledge, cManaPledge, addrress, nonce);
const apiClient = await this.buildApiClient();
const response = await apiClient.faucet({
accessManaPledgeID: aManaPledge,
consensusManaPledgeID: cManaPledge,
address: addrress,
nonce: nonce
});
this._done = true;
if (response.error) {
throw new Error(response.error);
}
await this.doUpdates();
});
}
Example #11
Source File: chatbox.ts From YoutubeLiveApp with MIT License | 6 votes |
(async () => {
const { app, chat }: { app: AppState; chat: ChatState } = await requestInitialState();
const reducer = combineReducers({ app: createAppReducer(app), chat: createChatReducer(chat) });
const store = createSharedStore(reducer);
store.subscribe(() => {
const state = store.getState();
if (state.chat.willInit && !state.chat.attached) {
store.dispatch(AttachChat());
const timer = setInterval(() => {
if (checkChatBoxVisible()) {
init();
clearInterval(timer);
}
}, 100);
}
});
console.log("waiting...");
function init() {
attachChatBox((element: HTMLElement) => {
const state = store.getState();
if (state.app.bouyomiChanEnabled) {
const chat = parseChatElement(element);
ipcRenderer.send(IPCEvent.BouyomiChan.SPEAK_BOUYOMICHAN_FROM_PRELOAD, chat);
}
if (element.localName !== "yt-live-chat-paid-message-renderer") {
return;
}
const superChatInfo = parseSuperChatElement(element);
const result = videoIdParseRegExp.exec(state.app.nowUrl);
if (result) {
const videoId = result[1];
store.dispatch(AppendSuperchat(videoId, superChatInfo));
}
});
}
})();
Example #12
Source File: ConfirmOptimizationModal.tsx From local-addon-image-optimizer with MIT License | 6 votes |
ConfirmOptimizationModal = (props: BaseModalProps & ModalContentsProps) => {
const { onSubmit, preferences } = props;
let displayText = 'Optimizing images will not strip metadata and will reduce image sizes to improve your site\'s performance.';
if (preferences.stripMetaData) {
displayText = 'Optimizing images will strip metadata and reduce image sizes to improve your site\'s performance.';
}
const openPreferencesModal = () => {
FlyModal.onRequestClose();
ipcRenderer.send(IPC_EVENTS.GO_TO_PREFERENCES);
};
return (
<div className='fileList_Modal'>
<Title size="l" container={{ margin: 'm 30 30' }}> Confirm Optimization </Title>
<Divider />
<div className='fileList_Modal_Text'>
{displayText}
<br />
<br />
<TextButton
className="fileList_Modal_Settings_Button"
onClick={openPreferencesModal}
>
View Settings
</TextButton>
</div>
<Divider />
<PrimaryButton
onClick={onSubmit}
>
Optimize Images
</PrimaryButton>
</div>
);
}
Example #13
Source File: site.ts From desktop with MIT License | 6 votes |
constructor(
public root: string,
public name: string = `Unnamed site`,
public hash: string = createContentDigest(root),
saveMetadata = false
) {
if (saveMetadata) {
this.saveMetadataToServiceConfig()
} else {
this.loadFromServiceConfig()
}
ipcRenderer.on(`site-message`, (event, hash: string, message: IMessage) => {
if (hash !== this.hash) {
// Not for us
return
}
if (
message?.type === `message` &&
message?.message?.type === IPCMessageType.LogAction
) {
this.handleMessage(message?.message?.action)
} else {
console.log(`Message received from worker`, message)
}
})
}
Example #14
Source File: ApplicationFrame.tsx From ace with GNU Affero General Public License v3.0 | 6 votes |
ApplicationFrame: FC = ({ children }) => {
const [isLocked, setIsLocked] = useState(false);
useEffect(() => {
ipcRenderer.send('update-rpc-permission', new AceConfigHandler().loadConfig().richPresenceEnabled);
}, []);
return (
<ApplicationTabsContext.Provider value={{ locked: isLocked, setLocked: setIsLocked }}>
<main className="w-full h-full flex flex-col">
<ApplicationTabs />
<ApplicationNotifications />
{children}
</main>
</ApplicationTabsContext.Provider>
);
}
Example #15
Source File: update-electron.ts From celo-web-wallet with MIT License | 6 votes |
ipcRenderer.on('update_downloaded', () => {
ipcRenderer.removeAllListeners('update_downloaded')
const updateBanner = document.getElementById('update-banner')
if (!updateBanner) {
logger.error('No update banner found')
return
}
updateBanner.style.display = 'block'
})
Example #16
Source File: electron.service.ts From blockcore-hub with MIT License | 6 votes |
constructor() {
if (this.isElectron) {
// const { BrowserWindow } = require('electron').remote
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
this.shell = window.require('electron').shell;
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
}
}
Example #17
Source File: preload.ts From noteworthy with GNU Affero General Public License v3.0 | 6 votes |
restrictedIpcRenderer: WindowAfterPreload["restrictedIpcRenderer"] = {
send: async (channel:string, ...data:any[]) => {
// whitelist channels
let validChannels: string[] = ["command"];
if (validChannels.includes(channel) || channel.startsWith("RENDER_DID_HANDLE")) {
console.log(`preload :: send() :: channel=${channel} :: ${data}`);
return await ipcRenderer.send(channel, ...data);
} else {
console.log(`preload :: send() :: invalid channel '${channel}'!`);
}
},
receive: (channel:string, listener: (...args: any[]) => void) => {
//let validChannels: string[] = [IpcEvents.RENDERER_INVOKE];
//TODO: (2021/03/05) send message over sub-channel instead of using prefix
if (channel.startsWith("RENDER_DID_HANDLE") || channel.startsWith(IpcEvents.RENDERER_INVOKE)) {
console.log(`preload :: attaching listener for channel=${channel}`);
// deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => {
console.log(`preload :: received message :: channel=${channel}`);
listener(...args);
});
} else {
console.log(`preload :: receive() :: invalid channel '${channel}'`);
}
},
invoke: async (channel:string, ...data:any[]) => {
let validChannels: string[] = ["command"];
if (validChannels.includes(channel)) {
console.log(`preload :: invoke() :: channel=${channel} :: ${data}`);
return await ipcRenderer.invoke(channel, ...data)
} else {
console.log(`preload :: invoke() :: invalid channel '${channel}' :: ${data}`);
}
}
}
Example #18
Source File: preload.ts From image-optimizer with MIT License | 6 votes |
contextBridge.exposeInMainWorld('electron', {
ipc: {
on: (channel: string, cb: EventCallback) => ipcRenderer.on(channel, cb),
send: (channel: string, data: any, cb?: EventCallback) => {
ipcRenderer.send(channel, data)
if (cb && typeof cb === 'function') {
ipcRenderer.on(channel, cb)
}
},
removeListener: (channel: string, cb: EventCallback) =>
ipcRenderer.removeListener(channel, cb),
removeListeners: (channel: string) =>
ipcRenderer.removeAllListeners(channel)
},
store: {
set: (key: any, value: any) => store.app.set(key, value),
get: (key: any) => store.app.get(key),
on: (key: any, cb: any) => store.app.onDidChange(key, cb)
}
})
Example #19
Source File: preload.ts From multi-downloader-nx with MIT License | 6 votes |
contextBridge.exposeInMainWorld('Electron', {
ipcRenderer: {
...ipcRenderer,
on: (name: string, handler: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => {
ipcRenderer.on(name, handler);
return ipcRenderer;
},
removeListener: (name: string, handler: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => {
ipcRenderer.removeListener(name, handler);
}
}
});
Example #20
Source File: preload.ts From animation-editor with MIT License | 6 votes |
contextBridge.exposeInMainWorld("electron", <ElectronGlobal>{
onDoubleClickDragArea: () => ipcRenderer.send("double-click-drag-area"),
registerUndo: (fn) => {
_onUndo = fn;
},
registerRedo: (fn) => {
_onRedo = fn;
},
});
Example #21
Source File: DatabaseManager.ts From cashcash-desktop with MIT License | 6 votes |
async importDatabaseFile(file: File) {
await this.resetConnection();
const path = file.path || (file as any).raw.path;
if (path === this.databasePath) {
throw new CashError("Can't import the same database file.");
}
ipcRenderer.send('importDatabase', {
newFilePath: path,
databasePath: this.databasePath,
});
}
Example #22
Source File: preload.ts From FIDO2Client with MIT License | 6 votes |
process.once('loaded', () => {
console.log(process.env);
if (process.platform === 'win32' && !(process.env && process.env['FIDO2_CLIENT_FORCE_PRELOAD'] === 'TRUE')) return;
if (!navigator.credentials) return;
const { get, create } = navigator.credentials;
Object.assign(navigator.credentials, {
create: async (options?: CredentialCreationOptions) => {
/**
* Only handle WebAuthn options, other options should fallback built-in handler
*/
if (typeof options?.publicKey !== 'object') return create(options);
/**
* Invoke create request to main process.
*/
const x = await ipcRenderer.invoke('navigator.credentials.create', options).catch(() => {
throw new DOMException('The operation either timed out or was not allowed. See: https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client.');
});
return x;
},
get: async (options?: CredentialRequestOptions) => {
/**
* Only handle WebAuthn options, other options should fallback built-in handler
*/
if (typeof options?.publicKey !== 'object') return get(options);
/**
* Invoke create request to main process.
*/
const x = await ipcRenderer.invoke('navigator.credentials.get', options).catch(() => {
throw new DOMException('The operation either timed out or was not allowed. See: https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client.');
});
return x;
}
});
});
Example #23
Source File: electron.service.ts From VIR with MIT License | 6 votes |
constructor() {
// Conditional imports
if (this.isElectron) {
this.ipcRenderer = window.require('electron').ipcRenderer
this.webFrame = window.require('electron').webFrame
// If you wan to use remote object, pleanse set enableRemoteModule to
// true in main.ts
this.remote = window.require('electron').remote
this.childProcess = window.require('child_process')
this.fs = window.require('fs')
this.os = window.require('os')
this.path = window.require('path')
}
}
Example #24
Source File: preload.ts From awakened-poe-trade with MIT License | 6 votes |
api: PreloadExposed = {
sendEvent (event) {
ipcRenderer.send(event.name, event.payload)
},
onEvent (cb) {
ipcRenderer.on('named-event', (_e, data) => {
cb(data)
})
},
getConfig () {
const name: IpcGetConfig['name'] = 'OVERLAY->MAIN::get-config'
return ipcRenderer.sendSync(name) as IpcGetConfig['payload']
},
importFile (filePath: string) {
const name: IpcImportFile['name'] = 'OVERLAY->MAIN::import-file'
return ipcRenderer.sendSync(name, filePath) as IpcImportFile['payload']
}
}
Example #25
Source File: reseed.ts From IYUU-GUI with GNU Affero General Public License v3.0 | 6 votes |
private async missionEnd() {
this.logger(`辅种任务已完成,任务Id: ${this.logId}`)
MissionStore.updateCurrentMissionState({
processing: false,
logId: this.logId
})
// 发送微信通知
if (this.options.weChatNotify) {
await this.sendWeChatNotify()
}
// 自动退出
if (this.options.closeAppAfterRun) {
ipcRenderer.send('close-me')
}
}
Example #26
Source File: electron.service.ts From msfs-community-downloader with GNU Affero General Public License v3.0 | 6 votes |
constructor() {
// Conditional imports
if (this.isElectron) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
// If you want to use remote object in renderer process, please set enableRemoteModule to true in main.ts
this.remote = window.require('@electron/remote');
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
}
}
Example #27
Source File: main.ts From project_nodeSnap with GNU General Public License v3.0 | 6 votes |
/**
* Init UI
*/
ipcRenderer.on("setId", (e, arg) => {
if (arg.id == "Main") {
const app = createApp(MainApp);
new TruckEditorManager();
app.use(router);
app.use(BootstrapIconsPlugin);
app.use(Toast, options);
app.use(store);
app.mount("#app");
app.config.globalProperties.$snapVersion = version;
} else if (arg.id == "Modal") {
//Modals stuff
const app = createApp(ModalApp);
app.use(router);
app.use(BootstrapIconsPlugin);
app.mount("#app");
}
});
Example #28
Source File: electron.service.ts From league-profile-tool with MIT License | 6 votes |
constructor() {
if (this.isElectron) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
this.shell = window.require('electron').shell;
this.request = window.require('request-promise');
this.dialog = window.require('electron').remote.dialog;
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
this.LCUConnector = window.require('lcu-connector');
}
}
Example #29
Source File: index.tsx From ExpressLRS-Configurator with GNU General Public License v3.0 | 6 votes |
LogsView: FunctionComponent = () => {
const onLogs = () => {
ipcRenderer.send(IpcRequest.OpenLogsFolder);
};
return (
<MainLayout>
<Card>
<CardTitle icon={<ListIcon />} title="Logs" />
<Divider />
<CardContent>
<Button
color="primary"
size="large"
variant="contained"
onClick={onLogs}
>
Open logs folder
</Button>
</CardContent>
</Card>
</MainLayout>
);
}