Electron官方文档(v1.6.1)中文翻译

14. session

2017-03-09  本文已影响361人  Shmily落墨

原文:https://github.com/electron/electron/blob/master/docs/api/session.md
译者:Lin

管理浏览器会话、cookie,缓存,代理设置等。

进程:主进程

session模块可以被用来创建新的Session对象。

你也可以通过使用WebContents的属性session来获取现存页面的session,或者从session模块获取。

const {BrowserWindow} = require('electron')

let win = new BrowserWindow({width: 800, height: 600})
win.loadURL('http://github.com')

const ses = win.webContents.session
console.log(ses.getUserAgent())

<h2 id="methods">方法</h2>

session模块有以下方法:

<h3 id="session-fromPartition"><code>session.fromPartition(partition[, options])</code></h3>

返回值为Session类型 - 从partition字符串获取的会话。当这里存在一个拥有同样的partitionSession,它将会被返回;否则一个新的Session实例将会通过options被创建。

如果partition是以persist:开头的,这个页面将会使用一个在应用中对所有页面的相同partition永久有效的会话。如果没有persist:前缀,页面将会使用内存会话。如果partition是空的,那么应用的默认会话将会被返回。

使用options创建一个Session,你必须保证Sessionpartition在之前从来没有被使用过。这里没有方法改变一个存在的Session对象的options

<h2 id="properties">属性</h2>

session模块有以下属性:

<h3 id="session-defaultSession"><code>session.defaultSession</code></h3>

一个Session对象,应用的默认会话对象。

<h2 id="class-session">类:Session</h2>

获取并设置一个会话的属性。

进程:主进程

你可以使用session模块来创建一个新的Session对象。

const {session} = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())

<h3 id="instance-events">实例的事件</h3>

以下事件在Session的实例中有效:

<h4 id="event-will-download">事件:'will-download'</h4>

Electron要下载webContents中的item的时候被分发。

调用event.preventDefault()将取消下载,并且item将从下一个进程标记起不再有效。

const {session} = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
    event.preventDefault()
    require('request')(item.getURL(), (data) => {
        require('fs').writeFileSync('/somewhere', data)
    })
})

<h3 id="instance-methods">实例的方法</h3>

以下方法在Session的实例中有效:

<h4 id="ses-getCacheSize"><code>ses.getCacheSize(callback)</code></h4>

回调会返回这个会话的当前缓存大小。

<h4 id="ses-clearCache"><code>ses.clearCache(callback)</code></h4>

清空会话的HTTP缓存。

<h4 id="ses-clearStorageData"><code>ses.clearStorageData([options, callback])</code></h4>

清除网络存储数据。

<h4 id="ses-flushStorageData"><code>ses.flushStorageData()</code></h4>

将还没有写入的DOMStorage写入磁盘。

<h4 id="ses-setProxy"><code>ses.setProxy(config, callback)</code></h4>

配置代理设置。

pacScriptproxyRules被一起提供,proxyRules选项被忽视,pacScript选项被应用。

proxyRules遵循以下规则:

proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]

例如:

proxyBypassRules是一个使用逗号分隔的列表,规则描述见下面:

<h4 id="ses-resolveProxy"><code>ses.resolveProxy(url, callback)</code></h4>

解析url的协议信息。当请求被执行的时候callback将要被callback(proxy)调用。

<h4 id="ses-setDownloadPath"><code>ses.setDownloadPath(path)</code></h4>

设置下载保存目录。默认情况下,下载目录将是在各自应用的文件夹中的Downloads文件夹下。

<h4 id="ses-enableNetworkEmulation"><code>ses.enableNetworkEmulation(options)</code></h4>

session中使用给定的配置模拟网络。

// 使用50kbps吞吐量和500ms延迟来模拟一个GPRS链接。
window.webContents.session.enableNetworkEmulation({
    latency: 500,
    downloadThroughput: 6400,
    uploadThroughput: 6400
})

// 模拟一个网络中断。
window.webContents.session.enableNetworkEmulation({offline: true})

<h4 id="ses-disableNetworkEmulation"><code>ses.disableNetworkEmulation()</code></h4>

禁用session中已经开启的网络模拟。将重置为原来的网络配置。

<h4 id="ses-setCertificateVerifyProc"><code>ses.setCertificateVerifyProc(proc)</code></h4>

设置session的证书验证过程,当一个服务器证书验证被请求,proc将会被proc(request, callback)调用 whenever a server certificate verification is requested. 调用callback(0)接受这个证书,调用callback(-2)拒绝这个证书。

调用setCertificateVerifyProc(null)将会恢复回默认的证书验证过程。

const {BrowserWindow} = require('electron')
let win = new BrowserWindow()

win.webContents.session.setCertificateVerifyProc((request, callback) => {
    const {hostname} = request
    if (hostname === 'github.com') {
        callback(0)
    } else {
        callback(-2)
    }
})

<h4 id="ses-setPermissionRequestHandler"><code>ses.setPermissionRequestHandler(handler)</code></h4>

设置session的许可请求的回复处理。调用callback(true)将允许这个许可,调用callback(false)将拒绝这个许可。

const {session} = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
    if (webContents.getURL() === 'some-host' && permission === 'notifications') {
        return callback(false) // denied.
    }

    callback(true)
})

<h4 id="ses-clearHostResolverCache"><code>ses.clearHostResolverCache([callback])</code></h4>

清空主机解析器的缓存。

<h4 id="ses-allowNTLMCredentialsForDomains"><code>ses.allowNTLMCredentialsForDomains(domains)</code></h4>

Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication.

const {session} = require('electron')
// 考虑到任何使用`example.com`, `foobar.com`, `baz`结尾的url的集成认证。
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')

// 考虑到所有的url的集成认证。
session.defaultSession.allowNTLMCredentialsForDomains('*')

<h4 id="ses-setUserAgent"><code>ses.setUserAgent(userAgent[, acceptLanguages])</code></h4>

重写这个会话的userAgentacceptLanguages

acceptLanguages必须是一个逗号分隔的语言代码的命令列表,例如:"en-US,fr,de,ko,zh-CN,ja"

这个不能影响到当前存在的WebContents,每个WebContents可以使用webContents.setUserAgent来重写会话范围内的用户代理。

<h4 id="ses-getUserAgent"><code>ses.getUserAgent()</code></h4>

返回值为String类型 - 这个会话的用户代理

<h4 id="ses-getBlobData"><code>ses.getBlobData(identifier, callback)</code></h4>

返回值为Blob类型 - 与identifier相关的blob数据。

<h4 id="ses-createInterruptedDownload"><code>ses.createInterruptedDownload(options)</code></h4>

允许在之前的Session中重新开始cancelledinterrupted下载。这个接口将生成一个可以被will-download事件使用的DownloadItemhttps://github.com/electron/electron/blob/master/docs/api/download-item.md。这个DownloadItem将没有任何和它相关的WebContents,并且最开始的状态将会被interrupted。这个下载将只在DownloadItem中调用resume接口时启动。

<h4 id="ses-clearAuthCache"><code>ses.clearAuthCache(options[, callback])</code></h4>

清空会话的HTTP验证缓存。

<h3 id="instance-properties">实例的属性</h3>

以下属性在Session的实例中有效:

<h4 id="ses-cookies"><code>ses.cookies</code></h4>

这个会话的Cookie对象。

<h4 id="ses-webRequest"><code>ses.webRequest</code></h4>

这个会话的WebRequest对象。

<h4 id="ses-protocol"><code>ses.protocol</code></h4>

这个会话的Protocol对象(一个protocol模块的实例)。

const {app, session} = require('electron')
const path = require('path')

app.on('ready', function () {
    const protocol = session.fromPartition('some-partition').protocol
    protocol.registerFileProtocol('atom', function (request, callback) {
        var url = request.url.substr(7)
        callback({path: path.normalize(`${__dirname}/${url}`)})
    }, function (error) {
        if (error) console.error('Failed to register protocol')
    })
})
上一篇 下一篇

猜你喜欢

热点阅读