本文整理汇总了TypeScript中electron.session.fromPartition方法的典型用法代码示例。如果您正苦于以下问题:TypeScript session.fromPartition方法的具体用法?TypeScript session.fromPartition怎么用?TypeScript session.fromPartition使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类electron.session
的用法示例。
在下文中一共展示了session.fromPartition方法的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);
});
示例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;
}
示例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
});
});
}
示例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"],
})
);
});
示例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}`);
}
}
示例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;
}
示例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
)}`
);
}
});
});
示例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);
});
//.........这里部分代码省略.........
示例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 });
}
};
//.........这里部分代码省略.........
示例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) {
//.........这里部分代码省略.........