electron#session JavaScript 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: index.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
createDataWindow = (url) => {
  const window = createWindow(url, {
    title: 'data: URL',
    width: 480,
    height: 360,
    webPreferences: {
      preload: null,
      session: session.fromPartition('unsafe-data-url')
    }
  });
  closeWindowWhenPressEscape(window);
  window.on('closed', () => {
    dataWindows.delete(window);
  });
  dataWindows.add(window);
}
Example #2
Source File: index.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
app.on('session-created', (session) => {
  session.setPermissionRequestHandler(handlePermissionRequest);

  session.on('will-download', (event, item, webContents) => {
    const extension = pathUtil.extname(item.getFilename()).replace(/^\./, '').toLowerCase();
    const extensionName = getTranslationOrNull(`files.${extension}`);
    if (extensionName) {
      item.setSaveDialogOptions({
        filters: [
          {
            name: extensionName,
            extensions: [extension]
          }
        ]
      });
    }
  });
});
Example #3
Source File: background.js    From EveReader with GNU Affero General Public License v3.0 6 votes vote down vote up
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      const vueExtension =
        process.cwd() + "/vue-devtools-5.3.3-Chrome-extension";
      await session.defaultSession.loadExtension(vueExtension);
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }

  await init();
});
Example #4
Source File: index.js    From clipcc-desktop with GNU Affero General Public License v3.0 5 votes vote down vote up
createWindow = ({search = null, url = 'index.html', ...browserWindowOptions}) => {
    const window = new BrowserWindow({
        useContentSize: true,
        show: false,
        webPreferences: {
            nodeIntegration: true,
            enableRemoteModule: true,
            contextIsolation: false,
            preload: path.resolve(path.join(__dirname, 'preload.js'))
        },
        ...browserWindowOptions
    });
    const webContents = window.webContents;
    remoteMain.enable(window.webContents);

    webContents.session.setPermissionRequestHandler(handlePermissionRequest);

    webContents.on('before-input-event', (event, input) => {
        if (input.code === devToolKey.code &&
            input.alt === devToolKey.alt &&
            input.control === devToolKey.control &&
            input.meta === devToolKey.meta &&
            input.shift === devToolKey.shift &&
            input.type === 'keyDown' &&
            !input.isAutoRepeat &&
            !input.isComposing) {
            event.preventDefault();
            webContents.openDevTools({mode: 'detach', activate: true});
        }
    });

    webContents.on('new-window', (event, newWindowUrl) => {
        shell.openExternal(newWindowUrl);
        event.preventDefault();
    });

    const fullUrl = makeFullUrl(url, search);
    window.loadURL(fullUrl);
    window.once('ready-to-show', () => {
        webContents.send('ready-to-show');
    });

    return window;
}
Example #5
Source File: index.js    From clipcc-desktop with GNU Affero General Public License v3.0 5 votes vote down vote up
// create main BrowserWindow when electron is ready
app.on('ready', () => {
    if (isDevelopment) {
        import('electron-devtools-installer').then(importedModule => {
            const {default: installExtension, ...devToolsExtensions} = importedModule;
            const extensionsToInstall = [
                devToolsExtensions.REACT_DEVELOPER_TOOLS,
                devToolsExtensions.REDUX_DEVTOOLS
            ];
            for (const extension of extensionsToInstall) {
                // WARNING: depending on a lot of things including the version of Electron `installExtension` might
                // return a promise that never resolves, especially if the extension is already installed.
                installExtension(extension)
                    .then(extensionName => log(`Installed dev extension: ${extensionName}`))
                    .catch(errorMessage => log.error(`Error installing dev extension: ${errorMessage}`));
            }
        });
    }

    _windows.main = createMainWindow();
    _windows.main.on('closed', () => {
        delete _windows.main;
        app.quit();
    });
    _windows.about = createAboutWindow();
    _windows.about.on('close', event => {
        event.preventDefault();
        _windows.about.hide();
    });
    _windows.privacy = createPrivacyWindow();
    _windows.privacy.on('close', event => {
        event.preventDefault();
        _windows.privacy.hide();
    });
    _windows.loading = createLoadingWindow();
    _windows.loading.on('closed', () => {
        delete _windows.loading;
        app.quit();
    });
    _windows.extensionStore = createExtensionStoneWindow();
    _windows.extensionStore.on('close', event => {
        event.preventDefault();
        _windows.extensionStore.hide();
    });
    const filter = {
        urls: ['*://codingclip.com/*']
    };
    session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
        details.requestHeaders['User-Agent'] = `ClipCCDesktop/${app.getVersion()}`;
        details.requestHeaders.Origin = null;
        callback({requestHeaders: details.requestHeaders});
    });
    session.defaultSession.webRequest.onHeadersReceived(filter, (details, callback) => {
        details.responseHeaders['Access-Control-Allow-Origin'] = ['*'];
        callback({responseHeaders: details.responseHeaders});
    });

});
Example #6
Source File: user.js    From brisque-2.0-desktop with MIT License 5 votes vote down vote up
logout() {
    session.fromPartition('persist:discord').clearStorageData();
    this.remove({}, { multi: true });
  }
Example #7
Source File: index.js    From clipcc-desktop with GNU Affero General Public License v3.0 4 votes vote down vote up
createMainWindow = () => {
    const window = createWindow({
        width: defaultSize.width,
        height: defaultSize.height,
        title: `${productName} ${version}` // something like "Scratch 3.14"
    });
    const webContents = window.webContents;

    webContents.session.on('will-download', (willDownloadEvent, downloadItem) => {
        const isProjectSave = getIsProjectSave(downloadItem);
        const itemPath = downloadItem.getFilename();
        const baseName = path.basename(itemPath);
        const extName = path.extname(baseName);
        const options = {
            defaultPath: baseName
        };
        if (extName) {
            const extNameNoDot = extName.replace(/^\./, '');
            options.filters = [getFilterForExtension(extNameNoDot)];
        }
        const userChosenPath = dialog.showSaveDialogSync(window, options);
        // this will be falsy if the user canceled the save
        if (userChosenPath) {
            const userBaseName = path.basename(userChosenPath);
            const tempPath = path.join(app.getPath('temp'), userBaseName);

            // WARNING: `setSavePath` on this item is only valid during the `will-download` event. Calling the async
            // version of `showSaveDialog` means the event will finish before we get here, so `setSavePath` will be
            // ignored. For that reason we need to call `showSaveDialogSync` above.
            downloadItem.setSavePath(tempPath);

            downloadItem.on('done', async (doneEvent, doneState) => {
                try {
                    if (doneState !== 'completed') {
                        // The download was canceled or interrupted. Cancel the telemetry event and delete the file.
                        throw new Error(`save ${doneState}`); // "save cancelled" or "save interrupted"
                    }
                    await fs.move(tempPath, userChosenPath, {overwrite: true});
                    if (isProjectSave) {
                        const newProjectTitle = path.basename(userChosenPath, extName);
                        webContents.send('setTitleFromSave', {title: newProjectTitle});

                        // "setTitleFromSave" will set the project title but GUI has already reported the telemetry
                        // event using the old title. This call lets the telemetry client know that the save was
                        // actually completed and the event should be committed to the event queue with this new title.
                        telemetry.projectSaveCompleted(newProjectTitle);
                    }
                } catch (e) {
                    if (isProjectSave) {
                        telemetry.projectSaveCanceled();
                    }
                    // don't clean up until after the message box to allow troubleshooting / recovery
                    await dialog.showMessageBox(window, {
                        type: 'error',
                        message: `Save failed:\n${userChosenPath}`,
                        detail: e.message
                    });
                    fs.exists(tempPath).then(exists => {
                        if (exists) {
                            fs.unlink(tempPath);
                        }
                    });
                }
            });
        } else {
            downloadItem.cancel();
            if (isProjectSave) {
                telemetry.projectSaveCanceled();
            }
        }
    });

    webContents.on('will-prevent-unload', ev => {
        const choice = dialog.showMessageBoxSync(window, {
            type: 'question',
            message: 'Leave ClipCC?',
            detail: 'Any unsaved changes will be lost.',
            buttons: ['Stay', 'Leave'],
            cancelId: 0, // closing the dialog means "stay"
            defaultId: 0 // pressing enter or space without explicitly selecting something means "stay"
        });
        const shouldQuit = (choice === 1);
        if (shouldQuit) {
            ev.preventDefault();
        }
    });

    window.once('ready-to-show', () => {
        _windows.loading.show();
    });
    webContents.once('did-finish-load', () => {
        _windows.loading.hide();
        window.show();
    });

    return window;
}