From 92faaf6d3466e9fe4e524c08779604c29ee43a2d Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 30 Aug 2023 17:19:54 +0100 Subject: [PATCH] Expose the desktop version & auth token synchronously Being able to wait once and then directly access this data synchronously is much better than needing to async every possible access to this data. --- src/preload.ts | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/preload.ts b/src/preload.ts index 640e968..bc3f639 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -2,11 +2,29 @@ import { contextBridge, ipcRenderer } from 'electron'; import type { ContextMenuDefinition } from './context-menu'; +// These are technically asynchronous, but they're so fast that +// they're effectively sychronously available - this seems to +// run before inline scripts in the page itself, let alone the +// main app code. Nonetheless, to be safe the UI can wait for +// the preload promise here to confirm it's definitely ready. +let desktopVersion: string | undefined; +let authToken: string | undefined; + +const preloadPromise = Promise.all([ + ipcRenderer.invoke('get-desktop-version').then(result => { + desktopVersion = result; + }), + ipcRenderer.invoke('get-server-auth-token').then(result => { + authToken = result; + }) +]); + contextBridge.exposeInMainWorld('desktopApi', { - desktopVersion: () => - ipcRenderer.invoke('get-desktop-version'), - serverAuthToken: () => - ipcRenderer.invoke('get-server-auth-token'), + waitUntilDesktopApiReady: () => preloadPromise.then(() => {}), + + getDesktopVersion: () => desktopVersion, + getServerAuthToken: () => authToken, + selectApplication: () => ipcRenderer.invoke('select-application'), openContextMenu: (options: ContextMenuDefinition) =>