Merge pull request #3514 from atom/session

Add session module
This commit is contained in:
Cheng Zhao 2015-11-20 10:23:38 +08:00
commit eec93665b7
12 changed files with 124 additions and 87 deletions

View file

@ -206,14 +206,6 @@ void App::OnWillFinishLaunching() {
} }
void App::OnFinishLaunching() { void App::OnFinishLaunching() {
// Create the defaultSession.
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto browser_context = static_cast<AtomBrowserContext*>(
AtomBrowserMainParts::Get()->browser_context());
auto handle = Session::CreateFrom(isolate(), browser_context);
default_session_.Reset(isolate(), handle.ToV8());
Emit("ready"); Emit("ready");
} }
@ -325,13 +317,6 @@ std::string App::GetLocale() {
return l10n_util::GetApplicationLocale(""); return l10n_util::GetApplicationLocale("");
} }
v8::Local<v8::Value> App::DefaultSession(v8::Isolate* isolate) {
if (default_session_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, default_session_);
}
bool App::MakeSingleInstance( bool App::MakeSingleInstance(
const ProcessSingleton::NotificationCallback& callback) { const ProcessSingleton::NotificationCallback& callback) {
if (process_singleton_.get()) if (process_singleton_.get())
@ -382,8 +367,7 @@ mate::ObjectTemplateBuilder App::GetObjectTemplateBuilder(
.SetMethod("allowNTLMCredentialsForAllDomains", .SetMethod("allowNTLMCredentialsForAllDomains",
&App::AllowNTLMCredentialsForAllDomains) &App::AllowNTLMCredentialsForAllDomains)
.SetMethod("getLocale", &App::GetLocale) .SetMethod("getLocale", &App::GetLocale)
.SetMethod("makeSingleInstance", &App::MakeSingleInstance) .SetMethod("makeSingleInstance", &App::MakeSingleInstance);
.SetProperty("defaultSession", &App::DefaultSession);
} }
// static // static

View file

@ -87,9 +87,6 @@ class App : public AtomBrowserClient::Delegate,
bool MakeSingleInstance( bool MakeSingleInstance(
const ProcessSingleton::NotificationCallback& callback); const ProcessSingleton::NotificationCallback& callback);
std::string GetLocale(); std::string GetLocale();
v8::Local<v8::Value> DefaultSession(v8::Isolate* isolate);
v8::Global<v8::Value> default_session_;
scoped_ptr<ProcessSingleton> process_singleton_; scoped_ptr<ProcessSingleton> process_singleton_;

View file

@ -1,18 +1,17 @@
electron = require 'electron' {deprecate, session, Menu} = require 'electron'
{EventEmitter} = require 'events' {EventEmitter} = require 'events'
bindings = process.atomBinding 'app' bindings = process.atomBinding 'app'
sessionBindings = process.atomBinding 'session'
downloadItemBindings = process.atomBinding 'download_item' downloadItemBindings = process.atomBinding 'download_item'
app = bindings.app app = bindings.app
app.__proto__ = EventEmitter.prototype app.__proto__ = EventEmitter.prototype
app.setApplicationMenu = (menu) -> app.setApplicationMenu = (menu) ->
electron.Menu.setApplicationMenu menu Menu.setApplicationMenu menu
app.getApplicationMenu = -> app.getApplicationMenu = ->
electron.Menu.getApplicationMenu() Menu.getApplicationMenu()
app.commandLine = app.commandLine =
appendSwitch: bindings.appendSwitch, appendSwitch: bindings.appendSwitch,
@ -35,9 +34,6 @@ app.setAppPath = (path) ->
app.getAppPath = -> app.getAppPath = ->
appPath appPath
# Helpers.
app.resolveProxy = (url, callback) -> @defaultSession.resolveProxy url, callback
# Routes the events to webContents. # Routes the events to webContents.
for name in ['login', 'certificate-error', 'select-client-certificate'] for name in ['login', 'certificate-error', 'select-client-certificate']
do (name) -> do (name) ->
@ -45,13 +41,14 @@ for name in ['login', 'certificate-error', 'select-client-certificate']
webContents.emit name, event, args... webContents.emit name, event, args...
# Deprecated. # Deprecated.
{deprecate} = electron
app.getHomeDir = deprecate 'app.getHomeDir', 'app.getPath', -> app.getHomeDir = deprecate 'app.getHomeDir', 'app.getPath', ->
@getPath 'home' @getPath 'home'
app.getDataPath = deprecate 'app.getDataPath', 'app.getPath', -> app.getDataPath = deprecate 'app.getDataPath', 'app.getPath', ->
@getPath 'userData' @getPath 'userData'
app.setDataPath = deprecate 'app.setDataPath', 'app.setPath', (path) -> app.setDataPath = deprecate 'app.setDataPath', 'app.setPath', (path) ->
@setPath 'userData', path @setPath 'userData', path
app.resolveProxy = deprecate 'app.resolveProxy', 'session.defaultSession.resolveProxy', (url, callback) ->
session.defaultSession.resolveProxy url, callback
deprecate.rename app, 'terminate', 'quit' deprecate.rename app, 'terminate', 'quit'
deprecate.event app, 'finish-launching', 'ready', -> deprecate.event app, 'finish-launching', 'ready', ->
setImmediate => # give default app a chance to setup default menu. setImmediate => # give default app a chance to setup default menu.
@ -61,11 +58,6 @@ deprecate.event app, 'activate-with-no-open-windows', 'activate', (event, hasVis
deprecate.event app, 'select-certificate', 'select-client-certificate' deprecate.event app, 'select-certificate', 'select-client-certificate'
# Wrappers for native classes. # Wrappers for native classes.
wrapSession = (session) ->
# session is an EventEmitter.
session.__proto__ = EventEmitter.prototype
sessionBindings._setWrapSession wrapSession
wrapDownloadItem = (downloadItem) -> wrapDownloadItem = (downloadItem) ->
# downloadItem is an EventEmitter. # downloadItem is an EventEmitter.
downloadItem.__proto__ = EventEmitter.prototype downloadItem.__proto__ = EventEmitter.prototype

View file

@ -1,10 +1,12 @@
{app, ipcMain, deprecate} = require 'electron' {ipcMain, deprecate} = require 'electron'
{EventEmitter} = require 'events' {EventEmitter} = require 'events'
{BrowserWindow} = process.atomBinding 'window' {BrowserWindow} = process.atomBinding 'window'
BrowserWindow::__proto__ = EventEmitter.prototype BrowserWindow::__proto__ = EventEmitter.prototype
BrowserWindow::_init = -> BrowserWindow::_init = ->
{app} = require 'electron' # avoid recursive require.
# Simulate the application menu on platforms other than OS X. # Simulate the application menu on platforms other than OS X.
if process.platform isnt 'darwin' if process.platform isnt 'darwin'
menu = app.getApplicationMenu() menu = app.getApplicationMenu()

View file

@ -42,6 +42,9 @@ Object.defineProperties module.exports,
screen: screen:
enumerable: true enumerable: true
get: -> require '../screen' get: -> require '../screen'
session:
enumerable: true
get: -> require '../session'
Tray: Tray:
enumerable: true enumerable: true
get: -> require '../tray' get: -> require '../tray'

View file

@ -0,0 +1,23 @@
{EventEmitter} = require 'events'
bindings = process.atomBinding 'session'
PERSIST_PERFIX = 'persist:'
# Returns the Session from |partition| string.
exports.fromPartition = (partition='') ->
if partition.startsWith PERSIST_PERFIX
bindings.fromPartition partition.substr(PERSIST_PERFIX.length), false
else
bindings.fromPartition partition, true
# Returns the default session.
Object.defineProperty exports, 'defaultSession',
enumerable: true
get: -> exports.fromPartition ''
wrapSession = (session) ->
# session is an EventEmitter.
session.__proto__ = EventEmitter.prototype
bindings._setWrapSession wrapSession

View file

@ -1,5 +1,5 @@
{EventEmitter} = require 'events' {EventEmitter} = require 'events'
{deprecate, ipcMain, NavigationController, Menu} = require 'electron' {deprecate, ipcMain, session, NavigationController, Menu} = require 'electron'
binding = process.atomBinding 'web_contents' binding = process.atomBinding 'web_contents'

View file

@ -311,14 +311,6 @@ preferred over `name` by Electron.
Returns the current application locale. Returns the current application locale.
### `app.resolveProxy(url, callback)`
* `url` URL
* `callback` Function
Resolves the proxy information for `url`. The `callback` will be called with
`callback(proxy)` when the request is performed.
### `app.addRecentDocument(path)` _OS X_ _Windows_ ### `app.addRecentDocument(path)` _OS X_ _Windows_
* `path` String * `path` String

View file

@ -1,8 +1,10 @@
# session # session
The `session` object is a property of [`webContents`](web-contents.md) which is The `session` module can be used to create new `Session` objects.
a property of [`BrowserWindow`](browser-window.md). You can access it through an
instance of `BrowserWindow`. For example: You can also access the `session` of existing pages by using the `session`
property of [`webContents`](web-contents.md) which is a property of
[`BrowserWindow`](browser-window.md).
```javascript ```javascript
const BrowserWindow = require('electron').BrowserWindow; const BrowserWindow = require('electron').BrowserWindow;
@ -10,12 +12,47 @@ const BrowserWindow = require('electron').BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600 }); var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL("http://github.com"); win.loadURL("http://github.com");
var session = win.webContents.session var ses = win.webContents.session
``` ```
## Events ## Methods
### Event: 'will-download' The `session` module has the following methods:
### session.fromPartition(partition)
* `partition` String
Returns a new `Session` instance from `partition` string.
If `partition` starts with `persist:`, the page will use a persistent session
available to all pages in the app with the same `partition`. if there is no
`persist:` prefix, the page will use an in-memory session. If the `partition` is
empty then default session of the app will be returned.
## Properties
The `session` module has the following properties:
### session.defaultSession
Returns the default session object of the app.
## Class: Session
You can create a `Session` object in the `session` module:
```javascript
const session = require('electron').session;
var ses = session.fromPartition('persist:name');
```
### Instance Events
The following events are available on instances of `Session`:
#### Event: 'will-download'
* `event` Event * `event` Event
* `item` [DownloadItem](download-item.md) * `item` [DownloadItem](download-item.md)
@ -34,11 +71,11 @@ session.on('will-download', function(event, item, webContents) {
}); });
``` ```
## Methods ### Instance Methods
The `session` object has the following methods: The following methods are available on instances of `Session`:
### `session.cookies` #### `ses.cookies`
The `cookies` gives you ability to query and modify cookies. For example: The `cookies` gives you ability to query and modify cookies. For example:
@ -74,7 +111,7 @@ win.webContents.on('did-finish-load', function() {
}); });
``` ```
### `session.cookies.get(details, callback)` #### `ses.cookies.get(details, callback)`
`details` Object, properties: `details` Object, properties:
@ -102,7 +139,7 @@ win.webContents.on('did-finish-load', function() {
the number of seconds since the UNIX epoch. Not provided for session the number of seconds since the UNIX epoch. Not provided for session
cookies. cookies.
### `session.cookies.set(details, callback)` #### `ses.cookies.set(details, callback)`
`details` Object, properties: `details` Object, properties:
@ -121,23 +158,23 @@ win.webContents.on('did-finish-load', function() {
* `callback` Function - function(error) * `callback` Function - function(error)
* `error` Error * `error` Error
### `session.cookies.remove(details, callback)` #### `ses.cookies.remove(details, callback)`
* `details` Object, proprties: * `details` Object
* `url` String - The URL associated with the cookie * `url` String - The URL associated with the cookie
* `name` String - The name of cookie to remove * `name` String - The name of cookie to remove
* `callback` Function - function(error) * `callback` Function - function(error)
* `error` Error * `error` Error
### `session.clearCache(callback)` #### `ses.clearCache(callback)`
* `callback` Function - Called when operation is done * `callback` Function - Called when operation is done
Clears the sessions HTTP cache. Clears the sessions HTTP cache.
### `session.clearStorageData([options, ]callback)` #### `ses.clearStorageData([options, ]callback)`
* `options` Object (optional), proprties: * `options` Object (optional)
* `origin` String - Should follow `window.location.origin`s representation * `origin` String - Should follow `window.location.origin`s representation
`scheme://host:port`. `scheme://host:port`.
* `storages` Array - The types of storages to clear, can contain: * `storages` Array - The types of storages to clear, can contain:
@ -149,7 +186,7 @@ Clears the sessions HTTP cache.
Clears the data of web storages. Clears the data of web storages.
### `session.setProxy(config, callback)` #### `ses.setProxy(config, callback)`
* `config` String * `config` String
* `callback` Function - Called when operation is done. * `callback` Function - Called when operation is done.
@ -187,14 +224,22 @@ proxy-uri = [<proxy-scheme>"://"]<proxy-host>[":"<proxy-port>]
URLs. URLs.
``` ```
### `session.setDownloadPath(path)` ### `ses.resolveProxy(url, callback)`
* `url` URL
* `callback` Function
Resolves the proxy information for `url`. The `callback` will be called with
`callback(proxy)` when the request is performed.
#### `ses.setDownloadPath(path)`
* `path` String - The download location * `path` String - The download location
Sets download saving directory. By default, the download directory will be the Sets download saving directory. By default, the download directory will be the
`Downloads` under the respective app folder. `Downloads` under the respective app folder.
### `session.enableNetworkEmulation(options)` #### `ses.enableNetworkEmulation(options)`
* `options` Object * `options` Object
* `offline` Boolean - Whether to emulate network outage. * `offline` Boolean - Whether to emulate network outage.
@ -216,12 +261,12 @@ window.webContents.session.enableNetworkEmulation({
window.webContents.session.enableNetworkEmulation({offline: true}); window.webContents.session.enableNetworkEmulation({offline: true});
``` ```
### `session.disableNetworkEmulation` #### `ses.disableNetworkEmulation()`
Disables any network emulation already active for the `session`. Resets to Disables any network emulation already active for the `session`. Resets to
the original network configuration. the original network configuration.
### `session.setCertificateVerifyProc(proc)` #### `ses.setCertificateVerifyProc(proc)`
* `proc` Function * `proc` Function

View file

@ -225,12 +225,6 @@ The usage is the same with [the `login` event of `app`](app.md#event-login).
The `webContents` object has the following instance methods: The `webContents` object has the following instance methods:
### `webContents.session`
Returns the `session` object used by this webContents.
See [session documentation](session.md) for this object's methods.
### `webContents.loadURL(url[, options])` ### `webContents.loadURL(url[, options])`
* `url` URL * `url` URL
@ -678,17 +672,6 @@ is in 32bit ARGB format).
End subscribing for frame presentation events. End subscribing for frame presentation events.
## Instance Properties
`WebContents` objects also have the following properties:
### `webContents.devToolsWebContents`
Get the `WebContents` of DevTools for this `WebContents`.
**Note:** Users should never store this object because it may become `null`
when the DevTools has been closed.
### `webContents.savePage(fullPath, saveType, callback)` ### `webContents.savePage(fullPath, saveType, callback)`
* `fullPath` String - The full file path. * `fullPath` String - The full file path.
@ -711,3 +694,18 @@ win.webContents.on('did-finish-load', function() {
}); });
}); });
``` ```
## Instance Properties
`WebContents` objects also have the following properties:
### `webContents.session`
Returns the [session](session.md) object used by this webContents.
### `webContents.devToolsWebContents`
Get the `WebContents` of DevTools for this `WebContents`.
**Note:** Users should never store this object because it may become `null`
when the DevTools has been closed.

View file

@ -26,6 +26,7 @@
'atom/browser/api/lib/power-monitor.coffee', 'atom/browser/api/lib/power-monitor.coffee',
'atom/browser/api/lib/power-save-blocker.coffee', 'atom/browser/api/lib/power-save-blocker.coffee',
'atom/browser/api/lib/protocol.coffee', 'atom/browser/api/lib/protocol.coffee',
'atom/browser/api/lib/session.coffee',
'atom/browser/api/lib/screen.coffee', 'atom/browser/api/lib/screen.coffee',
'atom/browser/api/lib/tray.coffee', 'atom/browser/api/lib/tray.coffee',
'atom/browser/api/lib/web-contents.coffee', 'atom/browser/api/lib/web-contents.coffee',

View file

@ -4,7 +4,7 @@ path = require 'path'
fs = require 'fs' fs = require 'fs'
{ipcRenderer, remote} = require 'electron' {ipcRenderer, remote} = require 'electron'
{app, ipcMain, BrowserWindow} = remote.require 'electron' {app, ipcMain, session, BrowserWindow} = remote
describe 'session module', -> describe 'session module', ->
@timeout 10000 @timeout 10000
@ -35,9 +35,9 @@ describe 'session module', ->
done('Can not find cookie') done('Can not find cookie')
it 'should over-write the existent cookie', (done) -> it 'should over-write the existent cookie', (done) ->
app.defaultSession.cookies.set {url: url, name: '1', value: '1'}, (error) -> session.defaultSession.cookies.set {url: url, name: '1', value: '1'}, (error) ->
return done(error) if error return done(error) if error
app.defaultSession.cookies.get {url: url}, (error, list) -> session.defaultSession.cookies.get {url: url}, (error, list) ->
return done(error) if error return done(error) if error
for cookie in list when cookie.name is '1' for cookie in list when cookie.name is '1'
if cookie.value is '1' if cookie.value is '1'
@ -47,11 +47,11 @@ describe 'session module', ->
done('Can not find cookie') done('Can not find cookie')
it 'should remove cookies', (done) -> it 'should remove cookies', (done) ->
app.defaultSession.cookies.set {url: url, name: '2', value: '2'}, (error) -> session.defaultSession.cookies.set {url: url, name: '2', value: '2'}, (error) ->
return done(error) if error return done(error) if error
app.defaultSession.cookies.remove {url: url, name: '2'}, (error) -> session.defaultSession.cookies.remove {url: url, name: '2'}, (error) ->
return done(error) if error return done(error) if error
app.defaultSession.cookies.get {url: url}, (error, list) -> session.defaultSession.cookies.get {url: url}, (error, list) ->
return done(error) if error return done(error) if error
for cookie in list when cookie.name is '2' for cookie in list when cookie.name is '2'
return done('Cookie not deleted') return done('Cookie not deleted')