context-bridge.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. const { getWebPreference } = process._linkedBinding('electron_renderer_web_frame');
  2. const binding = process._linkedBinding('electron_renderer_context_bridge');
  3. const contextIsolationEnabled = getWebPreference(window, 'contextIsolation');
  4. const checkContextIsolationEnabled = () => {
  5. if (!contextIsolationEnabled) throw new Error('contextBridge API can only be used when contextIsolation is enabled');
  6. };
  7. const contextBridge: Electron.ContextBridge = {
  8. exposeInMainWorld: (key: string, api: any) => {
  9. checkContextIsolationEnabled();
  10. return binding.exposeAPIInMainWorld(key, api);
  11. }
  12. } as any;
  13. export default contextBridge;
  14. export const internalContextBridge = {
  15. contextIsolationEnabled,
  16. overrideGlobalValueFromIsolatedWorld: (keys: string[], value: any) => {
  17. return binding._overrideGlobalValueFromIsolatedWorld(keys, value, false);
  18. },
  19. overrideGlobalValueWithDynamicPropsFromIsolatedWorld: (keys: string[], value: any) => {
  20. return binding._overrideGlobalValueFromIsolatedWorld(keys, value, true);
  21. },
  22. overrideGlobalPropertyFromIsolatedWorld: (keys: string[], getter: Function, setter?: Function) => {
  23. return binding._overrideGlobalPropertyFromIsolatedWorld(keys, getter, setter || null);
  24. },
  25. isInMainWorld: () => binding._isCalledFromMainWorld() as boolean
  26. };
  27. if (binding._isDebug) {
  28. contextBridge.internalContextBridge = internalContextBridge;
  29. }