當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript electron.session類代碼示例

本文整理匯總了TypeScript中electron.session的典型用法代碼示例。如果您正苦於以下問題:TypeScript session類的具體用法?TypeScript session怎麽用?TypeScript session使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了session類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: async

  watcher.on(actions.loginSucceeded, async (store, action) => {
    const userId = action.payload.profile.user.id;

    const { session } = require("electron");
    const partition = partitionForUser(String(userId));
    const ourSession = session.fromPartition(partition, { cache: true });
    await applyProxySettings(ourSession, store.getState().system);
  });
開發者ID:HorrerGames,項目名稱:itch,代碼行數:8,代碼來源:proxy.ts

示例2: getAppSession

function getAppSession(store: Store): Session {
  if (!_cachedAppSession) {
    _cachedAppSession = session.fromPartition(partitionForApp(), {
      cache: true,
    });

    // this works around https://github.com/itchio/itch/issues/2039
    registerItchProtocol(store, _cachedAppSession);
  }

  return _cachedAppSession;
}
開發者ID:itchio,項目名稱:itch,代碼行數:12,代碼來源:winds.ts

示例3: blockForPartition

	async function blockForPartition(partition: Partitions, baseUrl: string) {
		await initialization;
		const hostname = URL.parse(baseUrl).hostname;
		session.fromPartition(`persist:${partition}`, {
			cache: true
		}).webRequest.onBeforeRequest(FILTER_ALL, async (details, callback) => {
			const shouldBeBlocked = _block ? await shouldBlock(details, hostname) : false;
			callback({
				cancel: shouldBeBlocked
			});
		});
	}
開發者ID:SanderRonde,項目名稱:youtube-music-app,代碼行數:12,代碼來源:adblocking.ts

示例4: async

  watcher.on(actions.clearBrowsingData, async (store, action) => {
    const promises: Promise<any>[] = [];

    const userId = store.getState().profile.credentials.me.id;

    const partition = partitionForUser(String(userId));
    const ourSession = session.fromPartition(partition, { cache: true });

    logger.debug(`asked to clear browsing data`);

    if (action.payload.cache) {
      logger.debug(`clearing cache for ${partition}`);
      promises.push(
        new ItchPromise((resolve, reject) => {
          ourSession.clearCache(resolve);
        })
      );
    }

    if (action.payload.cookies) {
      logger.debug(`clearing cookies for ${partition}`);
      promises.push(
        new ItchPromise((resolve, reject) => {
          ourSession.clearStorageData(
            {
              storages: ["cookies"],
              // for all origins
              origin: null,
              // look chromium just clear everything thanks
              quotas: ["temporary", "persistent", "syncable"],
            },
            resolve
          );
        })
      );
    }

    await Promise.all(promises);

    store.dispatch(
      actions.statusMessage({
        message: ["prompt.clear_browsing_data.notification"],
      })
    );
  });
開發者ID:HorrerGames,項目名稱:itch,代碼行數:45,代碼來源:preferences.ts

示例5: loginSucceeded

async function loginSucceeded(store: Store, profile: Profile) {
  logger.info(`Login succeeded, setting up session`);
  try {
    const userId = profile.id;
    const partition = partitionForUser(String(userId));
    const customSession = session.fromPartition(partition, { cache: true });
    logger.info(`Registering itch protocol for session ${partition}`);
    registerItchProtocol(store, customSession);
  } catch (e) {
    logger.warn(`Could not register itch protocol for session: ${e.stack}`);
  }

  try {
    logger.info(`Restoring tabs...`);
    await restoreTabs(store, profile);
  } catch (e) {
    logger.warn(`Could not restore tabs: ${e.stack}`);
  }

  logger.info(`Dispatching login succeeded`);
  store.dispatch(actions.loginSucceeded({ profile }));

  try {
    logger.info(`Fetching owned keys...`);
    let t1 = Date.now();
    await mcall(
      messages.FetchProfileOwnedKeys,
      {
        profileId: profile.id,
        fresh: true,
        limit: 1,
      },
      convo => {
        hookLogging(convo, logger);
      }
    );
    let t2 = Date.now();
    logger.info(`Fetched owned keys in ${elapsed(t1, t2)}`);
    store.dispatch(actions.ownedKeysFetched({}));
  } catch (e) {
    logger.warn(`In initial owned keys fetch: ${e.stack}`);
  }
}
開發者ID:itchio,項目名稱:itch,代碼行數:43,代碼來源:login.ts

示例6: registerProtocol

export async function registerProtocol(opts: IRegisterProtocolOpts) {
  const { partition, fileRoot } = opts;

  if (registeredProtocols[partition]) {
    return;
  }

  const caveSession = session.fromPartition(partition, { cache: false });

  await new ItchPromise((resolve, reject) => {
    caveSession.protocol.registerFileProtocol(
      WEBGAME_PROTOCOL,
      (request, callback) => {
        const urlPath = url.parse(request.url).pathname;
        const decodedPath = decodeURI(urlPath);
        const rootlessPath = decodedPath.replace(/^\//, "");
        const filePath = join(fileRoot, rootlessPath);

        callback(filePath);
      },
      error => {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      }
    );
  });

  const handled = await new ItchPromise((resolve, reject) => {
    caveSession.protocol.isProtocolHandled(WEBGAME_PROTOCOL, result => {
      resolve(result);
    });
  });

  if (!handled) {
    throw new Error(`could not register custom protocol ${WEBGAME_PROTOCOL}`);
  }

  registeredProtocols[partition] = true;
}
開發者ID:HorrerGames,項目名稱:itch,代碼行數:42,代碼來源:itch-internal.ts

示例7: async

  watcher.on(actions.loginSucceeded, async (store, action) => {
    const userId = action.payload.profile.user.id;

    logger.debug(`Setting up for user ${userId}`);

    const session = electron.session.fromPartition(
      partitionForUser(String(userId)),
      { cache: true }
    );

    // requests to 'itch-internal' are used to communicate between web content & the app
    const internalFilter = {
      urls: ["https://itch-internal/*"],
    };

    session.webRequest.onBeforeRequest(internalFilter, (details, callback) => {
      callback({ cancel: true });

      let parsed = urlParser.parse(details.url);
      const { pathname, query } = parsed;
      const params = flattenQuery(querystring.parse(query));
      const { tab } = params;

      logger.debug(`Got itch-internal request ${pathname}?${query} for ${tab}`);

      if (pathname === "/open-devtools") {
        store.dispatch(actions.openDevTools({ forApp: false }));
      } else {
        logger.warn(
          `Got unrecognized message via itch-internal: ${pathname}, params ${JSON.stringify(
            params
          )}`
        );
      }
    });
  });
開發者ID:HorrerGames,項目名稱:itch,代碼行數:36,代碼來源:itch-internal.ts

示例8: performHTMLLaunch

export async function performHTMLLaunch(
  opts: HTMLLaunchOpts
): Promise<HTMLLaunchResult> {
  const { ctx, logger, game, params } = opts;
  const { rootFolder, indexPath, env, args } = params;

  // TODO: think if this is the right place to do that?
  let { width, height } = { width: 1280, height: 720 };
  const { embed } = game;
  if (embed && embed.width && embed.height) {
    width = embed.width;
    height = embed.height;
  }

  logger.info(`Performing HTML launch at resolution ${width}x${height}`);

  const partition = `persist:gamesession_${game.id}`;
  const gameSession = session.fromPartition(partition, { cache: false });

  await registerItchCaveProtocol(gameSession, rootFolder);

  // TODO: show game icon as, well, the window's icon
  let win = new BrowserWindow({
    title: game ? game.title : null,
    width,
    height,
    center: true,
    show: true,

    /* used to be black, but that didn't work for everything */
    backgroundColor: "#fff",

    /* the width x height we give is content size, window will be slightly larger */
    useContentSize: true,

    webPreferences: {
      /* don't let web code control the OS */
      nodeIntegration: false,
      /* hook up a few keyboard shortcuts of our own */
      preload: noPreload ? null : getInjectPath("game"),
      /* stores cookies etc. in persistent session to save progress */
      session: gameSession,
      /* disable CORS to allow access to the itch.io API */
      webSecurity: false,
    },
  });

  const itchObject = {
    env,
    args,
  };

  // open dev tools immediately if requested
  if (process.env.IMMEDIATE_NOSE_DIVE === "1") {
    win.webContents.openDevTools({ mode: "detach" });
  }
  win.setMenu(null);

  // strip 'Electron' from user agent so some web games stop being confused
  let userAgent = win.webContents.getUserAgent();
  userAgent = userAgent.replace(/Electron\/[0-9.]+\s/, "");
  win.webContents.setUserAgent(userAgent);

  const toggleFullscreen = () => {
    win.setFullScreen(!win.isFullScreen());
  };

  win.webContents.on(
    "before-input-event",
    (ev: Electron.Event, input: Electron.Input) => {
      if (input.type === "keyUp") {
        switch (input.key) {
          case "F11":
            toggleFullscreen();
            break;
          case "F":
            if (input.meta) {
              toggleFullscreen();
            }
            break;
          case "Escape":
            if (win.isFullScreen()) {
              win.setFullScreen(false);
            }
            break;
          case "F12":
            if (input.shift) {
              win.webContents.openDevTools({ mode: "detach" });
            }
            break;
        }
      }
    }
  );

  win.webContents.on("new-window", (ev: Event, url: string) => {
    ev.preventDefault();
    shell.openExternal(url);
  });

//.........這裏部分代碼省略.........
開發者ID:itchio,項目名稱:itch,代碼行數:101,代碼來源:perform-html-launch.ts

示例9: onBeforeSendHeaders

export const runWebRequestService = (window: BrowserWindow) => {
  mainWindow = window;

  const webviewRequest = session.fromPartition('persist:webviewsession')
    .webRequest;
  const defaultRequest = session.defaultSession.webRequest;

  session
    .fromPartition('persist:wexond_extension')
    .webRequest.onBeforeSendHeaders((details: any, callback: any) => {
      details.requestHeaders['User-Agent'] = global.userAgent;
      callback({ requestHeaders: details.requestHeaders, cancel: false });
    });

  // onBeforeSendHeaders

  const onBeforeSendHeaders = async (
    details: any,
    callback: any,
    isTabRelated: boolean,
  ) => {
    const requestHeaders = objectToArray(details.requestHeaders);

    const newDetails: any = {
      ...(await getDetails(details)),
      tabId: isTabRelated
        ? (await getTabByWebContentsId(window, details.webContentsId)).id
        : -1,
      requestHeaders,
    };

    const cb = getCallback(callback);

    const isIntercepted = interceptRequest(
      'onBeforeSendHeaders',
      newDetails,
      (res: any) => {
        if (res) {
          if (res.cancel) {
            cb({ cancel: true });
          } else if (res.requestHeaders) {
            const requestHeaders = arrayToObject(res.requestHeaders);
            cb({ requestHeaders, cancel: false });
          }
        }
        cb({ cancel: false, requestHeaders: details.requestHeaders });
      },
    );

    if (!isIntercepted) {
      cb({ cancel: false, requestHeaders: details.requestHeaders });
    }
  };

  defaultRequest.onBeforeSendHeaders(async (details: any, callback: any) => {
    await onBeforeSendHeaders(details, callback, false);
  });

  webviewRequest.onBeforeSendHeaders(async (details: any, callback: any) => {
    details.requestHeaders['User-Agent'] = global.userAgent;
    details.requestHeaders['DNT'] = '1';

    await onBeforeSendHeaders(details, callback, true);
  });

  // onBeforeRequest

  const onBeforeRequest = async (
    details: any,
    callback: any,
    isTabRelated: boolean,
  ) => {
    const newDetails: any = {
      ...(await getDetails(details)),
      tabId: isTabRelated
        ? (await getTabByWebContentsId(window, details.webContentsId)).id
        : -1,
    };
    const cb = getCallback(callback);

    const isIntercepted = interceptRequest(
      'onBeforeRequest',
      newDetails,
      (res: any) => {
        if (res) {
          if (res.cancel) {
            cb({ cancel: true });
          } else if (res.redirectUrl) {
            cb({ cancel: false, redirectURL: res.redirectUrl });
          }
        }
        cb({ cancel: false });
      },
    );

    if (!isIntercepted) {
      cb({ cancel: false });
    }
  };

//.........這裏部分代碼省略.........
開發者ID:laquereric,項目名稱:wexond,代碼行數:101,代碼來源:web-request.ts

示例10: async

  watcher.on(actions.preboot, async (store, action) => {
    let dispatchedBoot = false;

    let t1 = Date.now();
    try {
      const system: ISystemState = {
        appName: app.getName(),
        appVersion: app.getVersion().replace(/\-.*$/, ""),
        platform: os.itchPlatform(),
        arch: os.arch(),
        macos: os.platform() === "darwin",
        windows: os.platform() === "win32",
        linux: os.platform() === "linux",
        sniffedLanguage: app.getLocale(),
        homePath: app.getPath("home"),
        userDataPath: app.getPath("userData"),
        proxy: null,
        proxySource: null,
        quitting: false,
      };
      store.dispatch(actions.systemAssessed({ system }));

      try {
        await loadPreferences(store);
      } catch (e) {
        logger.error(
          `Could not load preferences: ${e.stack || e.message || e}`
        );
      }

      try {
        app.on(
          "certificate-error",
          (ev, webContents, url, error, certificate, callback) => {
            // do not trust
            callback(false);

            logger.error(
              `Certificate error: ${error} issued by ${
                certificate.issuerName
              } for ${certificate.subjectName}`
            );

            // TODO: that's super annoying as a modal.

            store.dispatch(
              actions.openModal(
                modalWidgets.naked.make({
                  window: "root",
                  title: `Certificate error: ${error}`,
                  message:
                    `There was an error with the certificate for ` +
                    `\`${certificate.subjectName}\` issued by \`${
                      certificate.issuerName
                    }\`.\n\n` +
                    `Please check your proxy configuration and try again.`,
                  detail: `If you ignore this error, the rest of the app might not work correctly.`,
                  buttons: [
                    {
                      label: "Ignore and continue",
                      className: "secondary",
                    },
                    {
                      label: ["menu.file.quit"],
                      action: actions.quit({}),
                    },
                  ],
                  widgetParams: null,
                })
              )
            );
          }
        );
        logger.debug(`Set up certificate error handler`);
      } catch (e) {
        logger.error(
          `Could not set up certificate error handler: ${e.stack ||
            e.message ||
            e}`
        );
      }

      try {
        const { session } = require("electron");
        const netSession = session.fromPartition(NET_PARTITION_NAME, {
          cache: false,
        });

        const envSettings: string =
          process.env.https_proxy ||
          process.env.HTTPS_PROXY ||
          process.env.http_proxy ||
          process.env.HTTP_PROXY;

        let proxySettings = {
          proxy: null as string,
          source: "os" as ProxySource,
        };

        if (envSettings) {
//.........這裏部分代碼省略.........
開發者ID:HorrerGames,項目名稱:itch,代碼行數:101,代碼來源:preboot.ts


注:本文中的electron.session類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。