electron#session TypeScript Examples

The following examples show how to use electron#session. 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: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
private onAddListener = (
    event: Electron.IpcMainInvokeEvent,
    extensionId: string,
    eventName: string
  ) => {
    const observer = this.sessionMap.get(event.sender.session)
    const listener: EventListener = { host: event.sender, extensionId }
    return observer?.addListener(listener, extensionId, eventName)
  }
Example #2
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    public session: Electron.Session,
    private delegate: RoutingDelegate = RoutingDelegate.get()
  ) {
    this.delegate.addObserver(this)

    session.on('extension-unloaded', (event, extension) => {
      this.filterListeners((listener) => listener.extensionId !== extension.id)
    })

    app.on('web-contents-created', (event, webContents) => {
      if (webContents.session === this.session && webContents.getType() === 'backgroundPage') {
        debug(`storing reference to background host [url:'${webContents.getURL()}']`)
        this.extensionHosts.add(webContents)
      }
    })
  }
Example #3
Source File: settings.ts    From fluent-reader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
function setProxy(address = null) {
    if (!address) {
        address = getProxy()
    } else {
        store.set(PAC_STORE_KEY, address)
    }
    if (getProxyStatus()) {
        let rules = { pacScript: address }
        session.defaultSession.setProxy(rules)
        session.fromPartition("sandbox").setProxy(rules)
    }
}
Example #4
Source File: main.ts    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
app.whenReady().then(async () => {
    console.log("START APP!!!!!!!! READY");

    if (isDev) {
        const devtools = await searchDevtools("REACT");
        if (devtools) {
            await session.defaultSession.loadExtension(devtools, {
                allowFileAccess: true,
            });
        }
    }
    createWindow();
});
Example #5
Source File: main.ts    From flect-chime-sdk-demo with Apache License 2.0 6 votes vote down vote up
app.whenReady().then(async () => {
	if (isDev) {
		const devtools = await searchDevtools('REACT');
		if (devtools) {
			await session.defaultSession.loadExtension(devtools, {
				allowFileAccess: true,
			});
		}
	}


    // await ffmpeg.load()
    // ffmpeg.setProgress((ratio:any) => {
    //     console.log("progress:", JSON.stringify(ratio));
    // });

	createWindow();
});
Example #6
Source File: index.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
public removeView = (workspaceID: string, windowName: WindowNames): void => {
    logger.debug(`Remove view for workspaceID ${workspaceID} via ${new Error('stack').stack ?? 'no stack'}`);
    const view = this.getView(workspaceID, windowName);
    const browserWindow = this.windowService.get(windowName);
    if (view !== undefined && browserWindow !== undefined) {
      void session.fromPartition(`persist:${workspaceID}`).clearStorageData();
      // stop find in page when switching workspaces
      view.webContents.stopFindInPage('clearSelection');
      view.webContents.send(WindowChannel.closeFindInPage);
      // currently use workaround https://github.com/electron/electron/issues/10096
      // eslint-disable-next-line unicorn/no-null
      browserWindow.setBrowserView(null);
      // @ts-expect-error Property 'destroy' does not exist on type 'WebContents'.ts(2339)
      // eslint-disable-next-line @typescript-eslint/no-unsafe-call
      view.webContents.destroy();
    }
    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
    delete this.views[workspaceID]![windowName];
  };
Example #7
Source File: index.ts    From electron-playground with MIT License 6 votes vote down vote up
function addDevToolsExtension(id: string) {
  if(!EXTENSION_FOLDER) return
  const extensionPath = path.resolve(EXTENSION_FOLDER, id)

  if (!existsSync(extensionPath)) {
    return
  }

  const versionName = readdirSync(extensionPath).find(
    v => existsSync(path.resolve(extensionPath, v)) && /\d+\.\d+\.\d/.test(v),
  )

  if (versionName) {
    session.defaultSession.loadExtension(path.resolve(extensionPath, versionName))
  }
}
Example #8
Source File: session.ts    From MagicUI with Apache License 2.0 6 votes vote down vote up
Session = {
  setCookies(name: string, value: string) {
    const Session = session.defaultSession;
    const Cookies = Session.cookies;

    return Cookies.set({
      url: domain,
      name,
      value,
    });
  },
  getCookies(name: string | null = null) {
    const Session = session.defaultSession;
    const Cookies = Session.cookies;
    if (!name) return Cookies.get({ url: domain });
    return Cookies.get({ url: domain, name });
  },
  clearCookies(name: string) {
    const Session = session.defaultSession;
    return Session.cookies.remove(domain, name);
  }
}
Example #9
Source File: session.ts    From MagicUI with Apache License 2.0 6 votes vote down vote up
export function setCookies(name: string, value: string) {
  const Session = session.defaultSession;
  const Cookies = Session.cookies;
  return Cookies.set({
    url: domain,
    name,
    value
  });
}
Example #10
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
constructor(
    public session: Electron.Session,
    private delegate: RoutingDelegate = RoutingDelegate.get()
  ) {
    this.delegate.addObserver(this)

    session.on('extension-unloaded', (event, extension) => {
      this.filterListeners((listener) => listener.extensionId !== extension.id)
    })

    app.on('web-contents-created', (event, webContents) => {
      if (webContents.session === this.session && webContents.getType() === 'backgroundPage') {
        debug(`storing reference to background host [url:'${webContents.getURL()}']`)
        this.extensionHosts.add(webContents)
      }
    })
  }
Example #11
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
async onExtensionMessage(
    event: Electron.IpcMainInvokeEvent,
    extensionId: string | undefined,
    handlerName: string,
    ...args: any[]
  ) {
    const { session } = this
    const { sender } = event
    const handler = this.getHandler(handlerName)

    if (sender.session !== session && !handler.allowRemote) {
      throw new Error(`${handlerName} does not support calling from a remote session`)
    }

    const extension = extensionId ? sender.session.getExtension(extensionId) : undefined
    if (!extension && handler.extensionContext) {
      throw new Error(`${handlerName} was sent from an unknown extension context`)
    }

    const extEvent = {
      sender,
      extension: extension!,
    }

    const result = await handler.callback(extEvent, ...args)

    debug(`${handlerName} result: %r`, result)

    return result
  }
Example #12
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
addListener(listener: EventListener, extensionId: string, eventName: string) {
    const { listeners, session } = this

    const extension = session.getExtension(extensionId)
    if (!extension) {
      throw new Error(`extension not registered in session [extensionId:${extensionId}]`)
    }

    if (!listeners.has(eventName)) {
      listeners.set(eventName, [])
    }

    const eventListeners = listeners.get(eventName)!
    const existingEventListener = eventListeners.find(eventListenerEquals(listener))

    if (existingEventListener) {
      debug(`ignoring existing '${eventName}' event listener for ${extensionId}`)
    } else {
      debug(`adding '${eventName}' event listener for ${extensionId}`)
      eventListeners.push(listener)
      this.observeListenerHost(listener.host)
    }
  }
Example #13
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
private onRemoveListener = (
    event: Electron.IpcMainInvokeEvent,
    extensionId: string,
    eventName: string
  ) => {
    const observer = this.sessionMap.get(event.sender.session)
    const listener: EventListener = { host: event.sender, extensionId }
    return observer?.removeListener(listener, extensionId, eventName)
  }
Example #14
Source File: main.ts    From animation-editor with MIT License 6 votes vote down vote up
app.on("ready", () => {
	Menu.setApplicationMenu(electronMenu);

	session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
		callback({
			responseHeaders: {
				...details.responseHeaders,
				// DevTools don't work when unsafe-eval is present. Commenting this out until I figure out
				// how to add a CSP without breaking DevTools or something else.
				//
				// "Content-Security-Policy": [
				// 	"default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self';",
				// ],

				// See https://developer.chrome.com/blog/enabling-shared-array-buffer/
				"Cross-Origin-Embedder-Policy": "require-corp",
				"Cross-Origin-Opener-Policy": "same-origin",
			},
		});
	});

	createElectronWindow();
});
Example #15
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
private onRemoteMessage = async (
    event: Electron.IpcMainInvokeEvent,
    sessionPartition: string,
    handlerName: string,
    ...args: any[]
  ) => {
    debug(`received remote '${handlerName}' for '${sessionPartition}'`, args)

    const ses =
      sessionPartition === DEFAULT_SESSION
        ? event.sender.session
        : session.fromPartition(sessionPartition)

    const observer = this.sessionMap.get(ses)

    return observer?.onExtensionMessage(event, undefined, handlerName, ...args)
  }
Example #16
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
private onRouterMessage = async (
    event: Electron.IpcMainInvokeEvent,
    extensionId: string,
    handlerName: string,
    ...args: any[]
  ) => {
    debug(`received '${handlerName}'`, args)

    const observer = this.sessionMap.get(event.sender.session)

    return observer?.onExtensionMessage(event, extensionId, handlerName, ...args)
  }
Example #17
Source File: setup.ts    From react-sqlite-app-starter with MIT License 6 votes vote down vote up
// Set a CSP up for our application based on the custom scheme
export function setupContentSecurityPolicy(customScheme: string): void {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          electronIsDev
            ? `default-src ${customScheme}://* 'unsafe-inline' devtools://* 'unsafe-eval' data:`
            : `default-src ${customScheme}://* 'unsafe-inline' data:`,
        ],
      },
    });
  });
}
Example #18
Source File: contentSecurityPolicy.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function setupContentSecurityPolicy (_: string): void {
  session.defaultSession.webRequest.onHeadersReceived((details, respond: (response: HeadersReceivedResponse) => void) => {
    respond({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          "default-src 'self';" +
          " style-src-elem 'self' https://fonts.googleapis.com/css 'unsafe-inline';" +
          " font-src data: 'self' https://fonts.gstatic.com;" +
          " style-src 'unsafe-inline';" +
          " connect-src 'self' wss: ws:;" +
          " img-src 'self' data:;" +
          // react-qr-reader uses an embedded blob
          " worker-src 'self' blob: filesystem:;" +
          // unsafe-eval is needed for the WASM content - same as the extension
          // script hashes here are for the window.top script (not technically needed)
          " script-src 'self' 'unsafe-eval' 'sha256-02/ejyoV/iwRdJ4NAsxjzF6WVUtLMPM6Nv96EbAm6u8=' 'sha256-wW/WsLudCDaPo/ibpeK0KslHqYpCzcAKNFxFBXwCHJg='"
        ]
      }
    });
  });
}
Example #19
Source File: index.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
createWindow = (): void => {
    session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
        // We abuse the `iframe` name attribute to sneak in the target URL, to later use as a proxy target
        details.requestHeaders['X-Ace-ProxyTarget'] = details.frame.name;

        callback({
            requestHeaders: details.requestHeaders,
        });
    });

    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        fullscreenable: true,
        frame: false,
        icon: 'extraResources/icon.ico',
        webPreferences: {
            webSecurity: false,
            nodeIntegration: true,
            enableRemoteModule: true,
            contextIsolation: false,
        },
    });

    mainWindow.setMenuBarVisibility(false);

    // and load the index.html of the app.
    mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);

    installExtension(REACT_DEVELOPER_TOOLS)
        .then((name) => console.log(`Added Extension:  ${name}`))
        .catch((err) => console.log('An error occurred: ', err));

    // Open the DevTools.
    mainWindow.webContents.openDevTools();
}
Example #20
Source File: electronHttpExecutor.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
createRequest(options: any, callback: (response: any) => void): any {

    // fix (node 7+) for making electron updater work when using AWS private buckets, check if headers contain Host property
    if (options.headers && options.headers.Host){
      // set host value from headers.Host
      options.host = options.headers.Host
      // remove header property 'Host', if not removed causes net::ERR_INVALID_ARGUMENT exception
      delete options.headers.Host;
    }

    // differential downloader can call this method very often, so, better to cache session
    if (this.cachedSession == null) {
      this.cachedSession = getNetSession()
    }

    const request = net.request({
      ...options,
      session: this.cachedSession,
    })
    request.on("response", callback)
    if (this.proxyLoginCallback != null) {
      request.on("login", this.proxyLoginCallback)
    }
    return request
  }
Example #21
Source File: setup.ts    From angular-sqlite-app-starter with MIT License 6 votes vote down vote up
// Set a CSP up for our application based on the custom scheme
export function setupContentSecurityPolicy(customScheme: string): void {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          electronIsDev
            ? `default-src ${customScheme}://* 'unsafe-inline' devtools://* 'unsafe-eval' data:`
            : `default-src ${customScheme}://* 'unsafe-inline' data:`,
        ],
      },
    });
  });
}
Example #22
Source File: index.ts    From DockerLocal with MIT License 6 votes vote down vote up
app.whenReady().then(() => {
  // automatically deny all permission requests from remote content 
  session.defaultSession.setPermissionRequestHandler((webcontents, permission, callback) => callback(false));
//   session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
//   callback({
//     responseHeaders: {
//       ...details.responseHeaders,
//       'Content-Security-Policy': ['default-src \'self\'']
//     }
//   })
// })


  installExtension(REACT_DEVELOPER_TOOLS)
    .then((devtool: any) => console.log(`Added Extension:  ${devtool.name}`))
    .catch((err: any) => console.log('An error occurred: ', err));
});
Example #23
Source File: crx-helpers.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
createCrxSession = () => {
  const partitionName = `crx-${uuid()}`
  const partition = `persist:${partitionName}`
  return {
    partitionName,
    partition,
    session: session.fromPartition(partition),
  }
}
Example #24
Source File: crx-helpers.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
createCrxRemoteWindow = () => {
  const sessionDetails = createCrxSession()
  addCrxPreload(sessionDetails.session)

  const win = new BrowserWindow({
    show: false,
    webPreferences: {
      session: sessionDetails.session,
      nodeIntegration: false,
      contextIsolation: true,
    },
  })

  return win
}
Example #25
Source File: extensions-spec.ts    From electron-browser-shell with GNU General Public License v3.0 6 votes vote down vote up
describe('Extensions', () => {
  const testSession = session.fromPartition('test-extensions')
  const extensions = new ElectronChromeExtensions({ session: testSession })

  it('retrieves the instance with fromSession()', () => {
    expect(ElectronChromeExtensions.fromSession(testSession)).to.equal(extensions)
  })

  it('throws when two instances are created for session', () => {
    expect(() => {
      new ElectronChromeExtensions({ session: testSession })
    }).to.throw()
  })
})
Example #26
Source File: index.ts    From shadowsocks-electron with GNU General Public License v3.0 5 votes vote down vote up
loadExtensionsManually = (paths: string[]) => {
  paths.forEach(async (_path) => {
    if (fs.existsSync(_path)) {
      await session.defaultSession.loadExtension(_path);
    }
  })
}
Example #27
Source File: session.ts    From MagicUI with Apache License 2.0 5 votes vote down vote up
export function getCookies(name: string | null = null) {
  const Session = session.defaultSession;
  const Cookies = Session.cookies;
  if (!name) return Cookies.get({ url: domain });
  return Cookies.get({ url: domain, name });
}
Example #28
Source File: index.ts    From shadowsocks-electron with GNU General Public License v3.0 5 votes vote down vote up
loadExtensions = (dirPath: string) => {
  const reactDevToolsPath = path.join(os.homedir(), dirPath);
  if (fs.existsSync(reactDevToolsPath)) {
    session.defaultSession.loadExtension(reactDevToolsPath);
  }
}
Example #29
Source File: router.ts    From electron-browser-shell with GNU General Public License v3.0 5 votes vote down vote up
addObserver(observer: RoutingDelegateObserver) {
    this.sessionMap.set(observer.session, observer)
  }