You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

4779 lines
166 KiB

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
this.EXPORTED_SYMBOLS = ["SessionStore"];
const Cu = Components.utils;
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const STATE_STOPPED = 0;
const STATE_RUNNING = 1;
const STATE_QUITTING = -1;
const STATE_STOPPED_STR = "stopped";
const STATE_RUNNING_STR = "running";
const TAB_STATE_NEEDS_RESTORE = 1;
const TAB_STATE_RESTORING = 2;
const PRIVACY_NONE = 0;
const PRIVACY_ENCRYPTED = 1;
const PRIVACY_FULL = 2;
const NOTIFY_WINDOWS_RESTORED = "sessionstore-windows-restored";
const NOTIFY_BROWSER_STATE_RESTORED = "sessionstore-browser-state-restored";
// Default maximum number of tabs to restore simultaneously. Controlled by
// the browser.sessionstore.max_concurrent_tabs pref.
const DEFAULT_MAX_CONCURRENT_TAB_RESTORES = 3;
// global notifications observed
const OBSERVING = [
"domwindowopened", "domwindowclosed",
"quit-application-requested", "quit-application-granted",
"browser-lastwindow-close-granted",
"quit-application", "browser:purge-session-history",
"browser:purge-domain-data"
];
// XUL Window properties to (re)store
// Restored in restoreDimensions()
const WINDOW_ATTRIBUTES = ["width", "height", "screenX", "screenY", "sizemode"];
// Hideable window features to (re)store
// Restored in restoreWindowFeatures()
const WINDOW_HIDEABLE_FEATURES = [
"menubar", "toolbar", "locationbar", "personalbar", "statusbar", "scrollbars"
];
const MESSAGES = [
// The content script tells us that its form data (or that of one of its
// subframes) might have changed. This can be the contents or values of
// standard form fields or of ContentEditables.
"SessionStore:input",
// The content script has received a pageshow event. This happens when a
// page is loaded from bfcache without any network activity, i.e. when
// clicking the back or forward button.
"SessionStore:pageshow"
];
// These are tab events that we listen to.
const TAB_EVENTS = [
"TabOpen", "TabClose", "TabSelect", "TabShow", "TabHide", "TabPinned",
"TabUnpinned"
];
#ifndef XP_WIN
#define BROKEN_WM_Z_ORDER
#endif
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
// debug.js adds NS_ASSERT. cf. bug 669196
Cu.import("resource://gre/modules/debug.js", this);
Cu.import("resource://gre/modules/osfile.jsm", this);
Cu.import("resource://gre/modules/PrivateBrowsingUtils.jsm", this);
Cu.import("resource://gre/modules/Promise.jsm", this);
XPCOMUtils.defineLazyServiceGetter(this, "gSessionStartup",
"@mozilla.org/browser/sessionstartup;1", "nsISessionStartup");
XPCOMUtils.defineLazyServiceGetter(this, "gScreenManager",
"@mozilla.org/gfx/screenmanager;1", "nsIScreenManager");
// List of docShell capabilities to (re)store. These are automatically
// retrieved from a given docShell if not already collected before.
// This is made so they're automatically in sync with all nsIDocShell.allow*
// properties.
var gDocShellCapabilities = (function() {
let caps;
return docShell => {
if (!caps) {
let keys = Object.keys(docShell);
caps = keys.filter(k => k.startsWith("allow")).map(k => k.slice(5));
}
return caps;
};
})();
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
#ifdef MOZ_DEVTOOLS
XPCOMUtils.defineLazyModuleGetter(this, "ScratchpadManager",
"resource://devtools/client/scratchpad/scratchpad-manager.jsm");
Object.defineProperty(this, "HUDService", {
get: function() {
let devtools = Cu.import("resource://devtools/shared/Loader.jsm", {}).devtools;
return devtools.require("devtools/client/webconsole/hudservice").HUDService;
},
configurable: true,
enumerable: true
});
#endif
XPCOMUtils.defineLazyModuleGetter(this, "DocumentUtils",
"resource:///modules/sessionstore/DocumentUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "SessionStorage",
"resource:///modules/sessionstore/SessionStorage.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "_SessionFile",
"resource:///modules/sessionstore/_SessionFile.jsm");
function debug(aMsg) {
aMsg = ("SessionStore: " + aMsg).replace(/\S{80}/g, "$&\n");
Services.console.logStringMessage(aMsg);
}
this.SessionStore = {
get promiseInitialized() {
return SessionStoreInternal.promiseInitialized.promise;
},
get canRestoreLastSession() {
return SessionStoreInternal.canRestoreLastSession;
},
set canRestoreLastSession(val) {
SessionStoreInternal.canRestoreLastSession = val;
},
init: function(aWindow) {
return SessionStoreInternal.init(aWindow);
},
getBrowserState: function() {
return SessionStoreInternal.getBrowserState();
},
setBrowserState: function(aState) {
SessionStoreInternal.setBrowserState(aState);
},
getWindowState: function(aWindow) {
return SessionStoreInternal.getWindowState(aWindow);
},
setWindowState: function(aWindow, aState, aOverwrite) {
SessionStoreInternal.setWindowState(aWindow, aState, aOverwrite);
},
getTabState: function(aTab) {
return SessionStoreInternal.getTabState(aTab);
},
setTabState: function(aTab, aState) {
SessionStoreInternal.setTabState(aTab, aState);
},
duplicateTab: function(aWindow, aTab, aDelta) {
return SessionStoreInternal.duplicateTab(aWindow, aTab, aDelta);
},
getClosedTabCount: function(aWindow) {
return SessionStoreInternal.getClosedTabCount(aWindow);
},
getClosedTabData: function(aWindow) {
return SessionStoreInternal.getClosedTabData(aWindow);
},
undoCloseTab: function(aWindow, aIndex) {
return SessionStoreInternal.undoCloseTab(aWindow, aIndex);
},
forgetClosedTab: function(aWindow, aIndex) {
return SessionStoreInternal.forgetClosedTab(aWindow, aIndex);
},
getClosedWindowCount: function() {
return SessionStoreInternal.getClosedWindowCount();
},
getClosedWindowData: function() {
return SessionStoreInternal.getClosedWindowData();
},
undoCloseWindow: function(aIndex) {
return SessionStoreInternal.undoCloseWindow(aIndex);
},
forgetClosedWindow: function(aIndex) {
return SessionStoreInternal.forgetClosedWindow(aIndex);
},
getWindowValue: function(aWindow, aKey) {
return SessionStoreInternal.getWindowValue(aWindow, aKey);
},
setWindowValue: function(aWindow, aKey, aStringValue) {
SessionStoreInternal.setWindowValue(aWindow, aKey, aStringValue);
},
deleteWindowValue: function(aWindow, aKey) {
SessionStoreInternal.deleteWindowValue(aWindow, aKey);
},
getTabValue: function(aTab, aKey) {
return SessionStoreInternal.getTabValue(aTab, aKey);
},
setTabValue: function(aTab, aKey, aStringValue) {
SessionStoreInternal.setTabValue(aTab, aKey, aStringValue);
},
deleteTabValue: function(aTab, aKey) {
SessionStoreInternal.deleteTabValue(aTab, aKey);
},
persistTabAttribute: function(aName) {
SessionStoreInternal.persistTabAttribute(aName);
},
restoreLastSession: function() {
SessionStoreInternal.restoreLastSession();
},
checkPrivacyLevel: function(aIsHTTPS, aUseDefaultPref) {
return SessionStoreInternal.checkPrivacyLevel(aIsHTTPS, aUseDefaultPref);
}
};
// Freeze the SessionStore object. We don't want anyone to modify it.
Object.freeze(SessionStore);
var SessionStoreInternal = {
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIDOMEventListener,
Ci.nsIObserver,
Ci.nsISupportsWeakReference
]),
// set default load state
_loadState: STATE_STOPPED,
// During the initial restore and setBrowserState calls tracks the number of
// windows yet to be restored
_restoreCount: -1,
// whether a setBrowserState call is in progress
_browserSetState: false,
// time in milliseconds (Date.now()) when the session was last written to file
_lastSaveTime: 0,
// time in milliseconds when the session was started (saved across sessions),
// defaults to now if no session was restored or timestamp doesn't exist
_sessionStartTime: Date.now(),
// states for all currently opened windows
_windows: {},
// internal states for all open windows (data we need to associate,
// but not write to disk)
_internalWindows: {},
// states for all recently closed windows
_closedWindows: [],
// not-"dirty" windows usually don't need to have their data updated
_dirtyWindows: {},
// collection of session states yet to be restored
_statesToRestore: {},
// counts the number of crashes since the last clean start
_recentCrashes: 0,
// whether the last window was closed and should be restored
_restoreLastWindow: false,
// number of tabs currently restoring
_tabsRestoringCount: 0,
// max number of tabs to restore concurrently
_maxConcurrentTabRestores: DEFAULT_MAX_CONCURRENT_TAB_RESTORES,
// whether restored tabs load cached versions or force a reload
_cacheBehavior: 0,
// The state from the previous session (after restoring pinned tabs). This
// state is persisted and passed through to the next session during an app
// restart to make the third party add-on warning not trash the deferred
// session
_lastSessionState: null,
// When starting Firefox with a single private window, this is the place
// where we keep the session we actually wanted to restore in case the user
// decides to later open a non-private window as well.
_deferredInitialState: null,
// A promise resolved once initialization is complete
_promiseInitialization: Promise.defer(),
// Whether session has been initialized
_sessionInitialized: false,
// True if session store is disabled by multi-process browsing.
// See bug 516755.
_disabledForMultiProcess: false,
// The original "sessionstore.resume_session_once" preference value before it
// was modified by saveState. saveState will set the
// "sessionstore.resume_session_once" to true when the
// the "sessionstore.resume_from_crash" preference is false (crash recovery
// is disabled) so that pinned tabs will be restored in the case of a
// crash. This variable is used to restore the original value so the
// previous session is not always restored when
// "sessionstore.resume_from_crash" is true.
_resume_session_once_on_shutdown: null,
/**
* A promise fulfilled once initialization is complete.
*/
get promiseInitialized() {
return this._promiseInitialization;
},
/* ........ Public Getters .............. */
get canRestoreLastSession() {
return this._lastSessionState;
},
set canRestoreLastSession(val) {
this._lastSessionState = null;
},
/* ........ Global Event Handlers .............. */
/**
* Initialize the component
*/
initService: function() {
if (this._sessionInitialized) {
return;
}
OBSERVING.forEach(function(aTopic) {
Services.obs.addObserver(this, aTopic, true);
}, this);
this._initPrefs();
this._disabledForMultiProcess = false;
// this pref is only read at startup, so no need to observe it
this._sessionhistory_max_entries =
this._prefBranch.getIntPref("sessionhistory.max_entries");
gSessionStartup.onceInitialized.then(
this.initSession.bind(this)
);
},
initSession: function() {
let ss = gSessionStartup;
try {
if (ss.doRestore() ||
ss.sessionType == Ci.nsISessionStartup.DEFER_SESSION)
this._initialState = ss.state;
}
catch(ex) { dump(ex + "\n"); } // no state to restore, which is ok
if (this._initialState) {
try {
// If we're doing a DEFERRED session, then we want to pull pinned tabs
// out so they can be restored.
if (ss.sessionType == Ci.nsISessionStartup.DEFER_SESSION) {
let [iniState, remainingState] = this._prepDataForDeferredRestore(this._initialState);
// If we have a iniState with windows, that means that we have windows
// with app tabs to restore.
if (iniState.windows.length)
this._initialState = iniState;
else
this._initialState = null;
if (remainingState.windows.length)
this._lastSessionState = remainingState;
}
else {
// Get the last deferred session in case the user still wants to
// restore it
this._lastSessionState = this._initialState.lastSessionState;
let lastSessionCrashed =
this._initialState.session && this._initialState.session.state &&
this._initialState.session.state == STATE_RUNNING_STR;
if (lastSessionCrashed) {
this._recentCrashes = (this._initialState.session &&
this._initialState.session.recentCrashes || 0) + 1;
if (this._needsRestorePage(this._initialState, this._recentCrashes)) {
// replace the crashed session with a restore-page-only session
let pageData = {
url: "about:sessionrestore",
formdata: {
id: { "sessionData": this._initialState },
xpath: {}
}
};
this._initialState = { windows: [{ tabs: [{ entries: [pageData] }] }] };
}
}
// Load the session start time from the previous state
this._sessionStartTime = this._initialState.session &&
this._initialState.session.startTime ||
this._sessionStartTime;
// make sure that at least the first window doesn't have anything hidden
delete this._initialState.windows[0].hidden;
// Since nothing is hidden in the first window, it cannot be a popup
delete this._initialState.windows[0].isPopup;
// We don't want to minimize and then open a window at startup.
if (this._initialState.windows[0].sizemode == "minimized")
this._initialState.windows[0].sizemode = "normal";
// clear any lastSessionWindowID attributes since those don't matter
// during normal restore
this._initialState.windows.forEach(function(aWindow) {
delete aWindow.__lastSessionWindowID;
});
}
}
catch (ex) { debug("The session file is invalid: " + ex); }
}
// A Lazy getter for the sessionstore.js backup promise.
XPCOMUtils.defineLazyGetter(this, "_backupSessionFileOnce", function() {
return _SessionFile.createBackupCopy();
});
// at this point, we've as good as resumed the session, so we can
// clear the resume_session_once flag, if it's set
if (this._loadState != STATE_QUITTING &&
this._prefBranch.getBoolPref("sessionstore.resume_session_once"))
this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
this._initEncoding();
// Session is ready.
this._sessionInitialized = true;
this._promiseInitialization.resolve();
},
_initEncoding : function() {
// The (UTF-8) encoder used to write to files.
XPCOMUtils.defineLazyGetter(this, "_writeFileEncoder", function() {
return new TextEncoder();
});
},
_initPrefs : function() {
XPCOMUtils.defineLazyGetter(this, "_prefBranch", function() {
return Services.prefs.getBranch("browser.");
});
// minimal interval between two save operations (in milliseconds)
XPCOMUtils.defineLazyGetter(this, "_interval", function() {
// used often, so caching/observing instead of fetching on-demand
this._prefBranch.addObserver("sessionstore.interval", this, true);
return this._prefBranch.getIntPref("sessionstore.interval");
});
// when crash recovery is disabled, session data is not written to disk
XPCOMUtils.defineLazyGetter(this, "_resume_from_crash", function() {
// get crash recovery state from prefs and allow for proper reaction to state changes
this._prefBranch.addObserver("sessionstore.resume_from_crash", this, true);
return this._prefBranch.getBoolPref("sessionstore.resume_from_crash");
});
this._max_tabs_undo = this._prefBranch.getIntPref("sessionstore.max_tabs_undo");
this._prefBranch.addObserver("sessionstore.max_tabs_undo", this, true);
this._max_windows_undo = this._prefBranch.getIntPref("sessionstore.max_windows_undo");
this._prefBranch.addObserver("sessionstore.max_windows_undo", this, true);
// Straight-up collect the following one-time prefs
this._maxConcurrentTabRestores =
Services.prefs.getIntPref("browser.sessionstore.max_concurrent_tabs");
// ensure a sane value for concurrency, ignore and set default otherwise
if (this._maxConcurrentTabRestores < 1 || this._maxConcurrentTabRestores > 10) {
this._maxConcurrentTabRestores = DEFAULT_MAX_CONCURRENT_TAB_RESTORES;
}
this._cacheBehavior =
Services.prefs.getIntPref("browser.sessionstore.cache_behavior");
},
_initWindow: function(aWindow) {
if (aWindow) {
this.onLoad(aWindow);
} else if (this._loadState == STATE_STOPPED) {
// If init is being called with a null window, it's possible that we
// just want to tell sessionstore that a session is live (as is the case
// with starting Firefox with -private, for example; see bug 568816),
// so we should mark the load state as running to make sure that
// things like setBrowserState calls will succeed in restoring the session.
this._loadState = STATE_RUNNING;
}
},
/**
* Start tracking a window.
*
* This function also initializes the component if it is not
* initialized yet.
*/
init: function(aWindow) {
let self = this;
this.initService();
return this._promiseInitialization.promise.then(
function onSuccess() {
self._initWindow(aWindow);
}
);
},
/**
* Called on application shutdown, after notifications:
* quit-application-granted, quit-application
*/
_uninit: function() {
// save all data for session resuming
if (this._sessionInitialized)
this.saveState(true);
// clear out priority queue in case it's still holding refs
TabRestoreQueue.reset();
// Make sure to break our cycle with the save timer
if (this._saveTimer) {
this._saveTimer.cancel();
this._saveTimer = null;
}
},
/**
* Handle notifications
*/
observe: function(aSubject, aTopic, aData) {
if (this._disabledForMultiProcess)
return;
switch (aTopic) {
case "domwindowopened": // catch new windows
this.onOpen(aSubject);
break;
case "domwindowclosed": // catch closed windows
this.onClose(aSubject);
break;
case "quit-application-requested":
this.onQuitApplicationRequested();
break;
case "quit-application-granted":
this.onQuitApplicationGranted();
break;
case "browser-lastwindow-close-granted":
this.onLastWindowCloseGranted();
break;
case "quit-application":
this.onQuitApplication(aData);
break;
case "browser:purge-session-history": // catch sanitization
this.onPurgeSessionHistory();
break;
case "browser:purge-domain-data":
this.onPurgeDomainData(aData);
break;
case "nsPref:changed": // catch pref changes
this.onPrefChange(aData);
break;
case "timer-callback": // timer call back for delayed saving
this.onTimerCallback();
break;
}
},
/**
* This method handles incoming messages sent by the session store content
* script and thus enables communication with OOP tabs.
*/
receiveMessage: function(aMessage) {
var browser = aMessage.target;
var win = browser.ownerDocument.defaultView;
switch (aMessage.name) {
case "SessionStore:pageshow":
this.onTabLoad(win, browser);
break;
case "SessionStore:input":
this.onTabInput(win, browser);
break;
default:
debug("received unknown message '" + aMessage.name + "'");
break;
}
this._clearRestoringWindows();
},
/* ........ Window Event Handlers .............. */
/**
* Implement nsIDOMEventListener for handling various window and tab events
*/
handleEvent: function(aEvent) {
if (this._disabledForMultiProcess)
return;
var win = aEvent.currentTarget.ownerDocument.defaultView;
switch (aEvent.type) {
case "load":
// If __SS_restore_data is set, then we need to restore the document
// (form data, scrolling, etc.). This will only happen when a tab is
// first restored.
let browser = aEvent.currentTarget;
if (browser.__SS_restore_data)
this.restoreDocument(win, browser, aEvent);
this.onTabLoad(win, browser);
break;
case "TabOpen":
this.onTabAdd(win, aEvent.originalTarget);
break;
case "TabClose":
// aEvent.detail determines if the tab was closed by moving to a different window
if (!aEvent.detail)
this.onTabClose(win, aEvent.originalTarget);
this.onTabRemove(win, aEvent.originalTarget);
break;
case "TabSelect":
this.onTabSelect(win);
break;
case "TabShow":
this.onTabShow(win, aEvent.originalTarget);
break;
case "TabHide":
this.onTabHide(win, aEvent.originalTarget);
break;
case "TabPinned":
case "TabUnpinned":
this.saveStateDelayed(win);
break;
}
this._clearRestoringWindows();
},
/**
* If it's the first window load since app start...
* - determine if we're reloading after a crash or a forced-restart
* - restore window state
* - restart downloads
* Set up event listeners for this window's tabs
* @param aWindow
* Window reference
*/
onLoad: function(aWindow) {
// return if window has already been initialized
if (aWindow && aWindow.__SSi && this._windows[aWindow.__SSi])
return;
// ignore non-browser windows and windows opened while shutting down
if (aWindow.document.documentElement.getAttribute("windowtype") != "navigator:browser" ||
this._loadState == STATE_QUITTING)
return;
// assign it a unique identifier (timestamp)
aWindow.__SSi = "window" + Date.now();
// and create its data object
this._windows[aWindow.__SSi] = { tabs: [], selected: 0, _closedTabs: [], busy: false };
// and create its internal data object
this._internalWindows[aWindow.__SSi] = { hosts: {} }
let isPrivateWindow = false;
if (PrivateBrowsingUtils.isWindowPrivate(aWindow))
this._windows[aWindow.__SSi].isPrivate = isPrivateWindow = true;
if (!this._isWindowLoaded(aWindow))
this._windows[aWindow.__SSi]._restoring = true;
if (!aWindow.toolbar.visible)
this._windows[aWindow.__SSi].isPopup = true;
// perform additional initialization when the first window is loading
if (this._loadState == STATE_STOPPED) {
this._loadState = STATE_RUNNING;
this._lastSaveTime = Date.now();
// restore a crashed session resp. resume the last session if requested
if (this._initialState) {
if (isPrivateWindow) {
// We're starting with a single private window. Save the state we
// actually wanted to restore so that we can do it later in case
// the user opens another, non-private window.
this._deferredInitialState = gSessionStartup.state;
delete this._initialState;
// Nothing to restore now, notify observers things are complete.
Services.obs.notifyObservers(null, NOTIFY_WINDOWS_RESTORED, "");
} else {
// make sure that the restored tabs are first in the window
this._initialState._firstTabs = true;
this._restoreCount = this._initialState.windows ? this._initialState.windows.length : 0;
this.restoreWindow(aWindow, this._initialState,
this._isCmdLineEmpty(aWindow, this._initialState));
delete this._initialState;
// _loadState changed from "stopped" to "running"
// force a save operation so that crashes happening during startup are correctly counted
this.saveState(true);
}
}
else {
// Nothing to restore, notify observers things are complete.
Services.obs.notifyObservers(null, NOTIFY_WINDOWS_RESTORED, "");
// the next delayed save request should execute immediately
this._lastSaveTime -= this._interval;
}
}
// this window was opened by _openWindowWithState
else if (!this._isWindowLoaded(aWindow)) {
let followUp = this._statesToRestore[aWindow.__SS_restoreID].windows.length == 1;
this.restoreWindow(aWindow, this._statesToRestore[aWindow.__SS_restoreID], true, followUp);
}
// The user opened another, non-private window after starting up with
// a single private one. Let's restore the session we actually wanted to
// restore at startup.
else if (this._deferredInitialState && !isPrivateWindow &&
aWindow.toolbar.visible) {
this._deferredInitialState._firstTabs = true;
this._restoreCount = this._deferredInitialState.windows ?
this._deferredInitialState.windows.length : 0;
this.restoreWindow(aWindow, this._deferredInitialState, false);
this._deferredInitialState = null;
}
else if (this._restoreLastWindow && aWindow.toolbar.visible &&
this._closedWindows.length && !isPrivateWindow) {
// default to the most-recently closed window
// don't use popup windows
let closedWindowState = null;
let closedWindowIndex;
for (let i = 0; i < this._closedWindows.length; i++) {
// Take the first non-popup, point our object at it, and break out.
if (!this._closedWindows[i].isPopup) {
closedWindowState = this._closedWindows[i];
closedWindowIndex = i;
break;
}
}
if (closedWindowState) {
let newWindowState;
if (!this._doResumeSession()) {
// We want to split the window up into pinned tabs and unpinned tabs.
// Pinned tabs should be restored. If there are any remaining tabs,
// they should be added back to _closedWindows.
// We'll cheat a little bit and reuse _prepDataForDeferredRestore
// even though it wasn't built exactly for this.
let [appTabsState, normalTabsState] =
this._prepDataForDeferredRestore({ windows: [closedWindowState] });
// These are our pinned tabs, which we should restore
if (appTabsState.windows.length) {
newWindowState = appTabsState.windows[0];
delete newWindowState.__lastSessionWindowID;
}
// In case there were no unpinned tabs, remove the window from _closedWindows
if (!normalTabsState.windows.length) {
this._closedWindows.splice(closedWindowIndex, 1);
}
// Or update _closedWindows with the modified state
else {
delete normalTabsState.windows[0].__lastSessionWindowID;
this._closedWindows[closedWindowIndex] = normalTabsState.windows[0];
}
}
else {
// If we're just restoring the window, make sure it gets removed from
// _closedWindows.
this._closedWindows.splice(closedWindowIndex, 1);
newWindowState = closedWindowState;
delete newWindowState.hidden;
}
if (newWindowState) {
// Ensure that the window state isn't hidden
this._restoreCount = 1;
let state = { windows: [newWindowState] };
this.restoreWindow(aWindow, state, this._isCmdLineEmpty(aWindow, state));
}
}
// we actually restored the session just now.
this._prefBranch.setBoolPref("sessionstore.resume_session_once", false);
}
if (this._restoreLastWindow && aWindow.toolbar.visible) {
// always reset (if not a popup window)
// we don't want to restore a window directly after, for example,
// undoCloseWindow was executed.
this._restoreLastWindow = false;
}
var tabbrowser = aWindow.gBrowser;
// add tab change listeners to all already existing tabs
for (let i = 0; i < tabbrowser.tabs.length; i++) {
this.onTabAdd(aWindow, tabbrowser.tabs[i], true);
}
// notification of tab add/remove/selection/show/hide
TAB_EVENTS.forEach(function(aEvent) {
tabbrowser.tabContainer.addEventListener(aEvent, this, true);
}, this);
},
/**
* On window open
* @param aWindow
* Window reference
*/
onOpen: function(aWindow) {
var _this = this;
aWindow.addEventListener("load", function(aEvent) {
aEvent.currentTarget.removeEventListener("load", arguments.callee, false);
_this.onLoad(aEvent.currentTarget);
}, false);
return;
},
/**
* On window close...
* - remove event listeners from tabs
* - save all window data
* @param aWindow
* Window reference
*/
onClose: function(aWindow) {
// this window was about to be restored - conserve its original data, if any
let isFullyLoaded = this._isWindowLoaded(aWindow);
if (!isFullyLoaded) {
if (!aWindow.__SSi)
aWindow.__SSi = "window" + Date.now();
this._windows[aWindow.__SSi] = this._statesToRestore[aWindow.__SS_restoreID];
delete this._statesToRestore[aWindow.__SS_restoreID];
delete aWindow.__SS_restoreID;
}
// ignore windows not tracked by SessionStore
if (!aWindow.__SSi || !this._windows[aWindow.__SSi]) {
return;
}
// notify that the session store will stop tracking this window so that
// extensions can store any data about this window in session store before
// that's not possible anymore
let event = aWindow.document.createEvent("Events");
event.initEvent("SSWindowClosing", true, false);
aWindow.dispatchEvent(event);
if (this.windowToFocus && this.windowToFocus == aWindow) {
delete this.windowToFocus;
}
var tabbrowser = aWindow.gBrowser;
TAB_EVENTS.forEach(function(aEvent) {
tabbrowser.tabContainer.removeEventListener(aEvent, this, true);
}, this);
// remove the progress listener for this window
tabbrowser.removeTabsProgressListener(gRestoreTabsProgressListener);
let winData = this._windows[aWindow.__SSi];
if (this._loadState == STATE_RUNNING) { // window not closed during a regular shut-down
// update all window data for a last time
this._collectWindowData(aWindow);
if (isFullyLoaded) {
winData.title = aWindow.content.document.title || tabbrowser.selectedTab.label;
winData.title = this._replaceLoadingTitle(winData.title, tabbrowser,
tabbrowser.selectedTab);
let windows = {};
windows[aWindow.__SSi] = winData;
this._updateCookies(windows);
}
// Until we decide otherwise elsewhere, this window is part of a series
// of closing windows to quit.
winData._shouldRestore = true;
// Save the window if it has multiple tabs or a single saveable tab and
// it's not private.
if (!winData.isPrivate && (winData.tabs.length > 1 ||
(winData.tabs.length == 1 && this._shouldSaveTabState(winData.tabs[0])))) {
// we don't want to save the busy state
delete winData.busy;
this._closedWindows.unshift(winData);
this._capClosedWindows();
}
// clear this window from the list
delete this._windows[aWindow.__SSi];
delete this._internalWindows[aWindow.__SSi];
// save the state without this window to disk
this.saveStateDelayed();
}
for (let i = 0; i < tabbrowser.tabs.length; i++) {
this.onTabRemove(aWindow, tabbrowser.tabs[i], true);
}
// Cache the window state until it is completely gone.
DyingWindowCache.set(aWindow, winData);
delete aWindow.__SSi;
},
/**
* On quit application requested
*/
onQuitApplicationRequested: function() {
// get a current snapshot of all windows
this._forEachBrowserWindow(function(aWindow) {
this._collectWindowData(aWindow);
});
// we must cache this because _getMostRecentBrowserWindow will always
// return null by the time quit-application occurs
var activeWindow = this._getMostRecentBrowserWindow();
if (activeWindow)
this.activeWindowSSiCache = activeWindow.__SSi || "";
this._dirtyWindows = [];
},
/**
* On quit application granted
*/
onQuitApplicationGranted: function() {
// freeze the data at what we've got (ignoring closing windows)
this._loadState = STATE_QUITTING;
},
/**
* On last browser window close
*/
onLastWindowCloseGranted: function() {
// last browser window is quitting.
// remember to restore the last window when another browser window is opened
// do not account for pref(resume_session_once) at this point, as it might be
// set by another observer getting this notice after us
this._restoreLastWindow = true;
},
/**
* On quitting application
* @param aData
* String type of quitting
*/
onQuitApplication: function(aData) {
if (aData == "restart") {
this._prefBranch.setBoolPref("sessionstore.resume_session_once", true);
// The browser:purge-session-history notification fires after the
// quit-application notification so unregister the
// browser:purge-session-history notification to prevent clearing
// session data on disk on a restart. It is also unnecessary to
// perform any other sanitization processing on a restart as the
// browser is about to exit anyway.
Services.obs.removeObserver(this, "browser:purge-session-history");
}
else if (this._resume_session_once_on_shutdown != null) {
// if the sessionstore.resume_session_once preference was changed by
// saveState because crash recovery is disabled then restore the
// preference back to the value it was prior to that. This will prevent
// SessionStore from always restoring the session when crash recovery is
// disabled.
this._prefBranch.setBoolPref("sessionstore.resume_session_once",
this._resume_session_once_on_shutdown);
}
if (aData != "restart") {
// Throw away the previous session on shutdown
this._lastSessionState = null;
}
this._loadState = STATE_QUITTING; // just to be sure
this._uninit();
},
/**
* On purge of session history
*/
onPurgeSessionHistory: function() {
var _this = this;
_SessionFile.wipe();
// If the browser is shutting down, simply return after clearing the
// session data on disk as this notification fires after the
// quit-application notification so the browser is about to exit.
if (this._loadState == STATE_QUITTING)
return;
this._lastSessionState = null;
let openWindows = {};
this._forEachBrowserWindow(function(aWindow) {
Array.forEach(aWindow.gBrowser.tabs, function(aTab) {
delete aTab.linkedBrowser.__SS_data;
delete aTab.linkedBrowser.__SS_tabStillLoading;
delete aTab.linkedBrowser.__SS_formDataSaved;
delete aTab.linkedBrowser.__SS_hostSchemeData;
if (aTab.linkedBrowser.__SS_restoreState)
this._resetTabRestoringState(aTab);
}, this);
openWindows[aWindow.__SSi] = true;
});
// also clear all data about closed tabs and windows
for (let ix in this._windows) {
if (ix in openWindows) {
this._windows[ix]._closedTabs = [];
}
else {
delete this._windows[ix];
delete this._internalWindows[ix];
}
}
// also clear all data about closed windows
this._closedWindows = [];
// give the tabbrowsers a chance to clear their histories first
var win = this._getMostRecentBrowserWindow();
if (win)
win.setTimeout(function() { _this.saveState(true); }, 0);
else if (this._loadState == STATE_RUNNING)
this.saveState(true);
// Delete the private browsing backed up state, if any
if ("_stateBackup" in this)
delete this._stateBackup;
this._clearRestoringWindows();
},
/**
* On purge of domain data
* @param aData
* String domain data
*/
onPurgeDomainData: function(aData) {
// does a session history entry contain a url for the given domain?
function containsDomain(aEntry) {
try {
if (this._getURIFromString(aEntry.url).host.hasRootDomain(aData))
return true;
}
catch (ex) { /* url had no host at all */ }
return aEntry.children && aEntry.children.some(containsDomain, this);
}
// remove all closed tabs containing a reference to the given domain
for (let ix in this._windows) {
let closedTabs = this._windows[ix]._closedTabs;
for (let i = closedTabs.length - 1; i >= 0; i--) {
if (closedTabs[i].state.entries.some(containsDomain, this))
closedTabs.splice(i, 1);
}
}
// remove all open & closed tabs containing a reference to the given
// domain in closed windows
for (let ix = this._closedWindows.length - 1; ix >= 0; ix--) {
let closedTabs = this._closedWindows[ix]._closedTabs;
let openTabs = this._closedWindows[ix].tabs;
let openTabCount = openTabs.length;
for (let i = closedTabs.length - 1; i >= 0; i--)
if (closedTabs[i].state.entries.some(containsDomain, this))
closedTabs.splice(i, 1);
for (let j = openTabs.length - 1; j >= 0; j--) {
if (openTabs[j].entries.some(containsDomain, this)) {
openTabs.splice(j, 1);
if (this._closedWindows[ix].selected > j)
this._closedWindows[ix].selected--;
}
}
if (openTabs.length == 0) {
this._closedWindows.splice(ix, 1);
}
else if (openTabs.length != openTabCount) {
// Adjust the window's title if we removed an open tab
let selectedTab = openTabs[this._closedWindows[ix].selected - 1];
// some duplication from restoreHistory - make sure we get the correct title
let activeIndex = (selectedTab.index || selectedTab.entries.length) - 1;
if (activeIndex >= selectedTab.entries.length)
activeIndex = selectedTab.entries.length - 1;
this._closedWindows[ix].title = selectedTab.entries[activeIndex].title;
}
}
if (this._loadState == STATE_RUNNING)
this.saveState(true);
this._clearRestoringWindows();
},
/**
* On preference change
* @param aData
* String preference changed
*/
onPrefChange: function(aData) {
switch (aData) {
// if the user decreases the max number of closed tabs they want
// preserved update our internal states to match that max
case "sessionstore.max_tabs_undo":
this._max_tabs_undo = this._prefBranch.getIntPref("sessionstore.max_tabs_undo");
for (let ix in this._windows) {
this._windows[ix]._closedTabs.splice(this._max_tabs_undo, this._windows[ix]._closedTabs.length);
}
break;
case "sessionstore.max_windows_undo":
this._max_windows_undo = this._prefBranch.getIntPref("sessionstore.max_windows_undo");
this._capClosedWindows();
break;
case "sessionstore.interval":
this._interval = this._prefBranch.getIntPref("sessionstore.interval");
// reset timer and save
if (this._saveTimer) {
this._saveTimer.cancel();
this._saveTimer = null;
}
this.saveStateDelayed(null, -1);
break;
case "sessionstore.resume_from_crash":
this._resume_from_crash = this._prefBranch.getBoolPref("sessionstore.resume_from_crash");
// restore original resume_session_once preference if set in saveState
if (this._resume_session_once_on_shutdown != null) {
this._prefBranch.setBoolPref("sessionstore.resume_session_once",
this._resume_session_once_on_shutdown);
this._resume_session_once_on_shutdown = null;
}
// either create the file with crash recovery information or remove it
// (when _loadState is not STATE_RUNNING, that file is used for session resuming instead)
if (!this._resume_from_crash)
_SessionFile.wipe();
this.saveState(true);
break;
}
},
/**
* On timer callback
*/
onTimerCallback: function() {
this._saveTimer = null;
this.saveState();
},
/**
* set up listeners for a new tab
* @param aWindow
* Window reference
* @param aTab
* Tab reference
* @param aNoNotification
* bool Do not save state if we're updating an existing tab
*/
onTabAdd: function(aWindow, aTab, aNoNotification) {
let browser = aTab.linkedBrowser;
browser.addEventListener("load", this, true);
let mm = browser.messageManager;
MESSAGES.forEach(msg => mm.addMessageListener(msg, this));
if (!aNoNotification) {
this.saveStateDelayed(aWindow);
}
},
/**
* remove listeners for a tab
* @param aWindow
* Window reference
* @param aTab
* Tab reference
* @param aNoNotification
* bool Do not save state if we're updating an existing tab
*/
onTabRemove: function(aWindow, aTab, aNoNotification) {
let browser = aTab.linkedBrowser;
browser.removeEventListener("load", this, true);
let mm = browser.messageManager;
MESSAGES.forEach(msg => mm.removeMessageListener(msg, this));
delete browser.__SS_data;
delete browser.__SS_tabStillLoading;
delete browser.__SS_formDataSaved;
delete browser.__SS_hostSchemeData;
// If this tab was in the middle of restoring or still needs to be restored,
// we need to reset that state. If the tab was restoring, we will attempt to
// restore the next tab.
let previousState = browser.__SS_restoreState;
if (previousState) {
this._resetTabRestoringState(aTab);
if (previousState == TAB_STATE_RESTORING)
this.restoreNextTab();
}
if (!aNoNotification) {
this.saveStateDelayed(aWindow);
}
},
/**
* When a tab closes, collect its properties
* @param aWindow
* Window reference
* @param aTab
* Tab reference
*/
onTabClose: function(aWindow, aTab) {
// notify the tabbrowser that the tab state will be retrieved for the last time
// (so that extension authors can easily set data on soon-to-be-closed tabs)
var event = aWindow.document.createEvent("Events");
event.initEvent("SSTabClosing", true, false);
aTab.dispatchEvent(event);
// don't update our internal state if we don't have to
if (this._max_tabs_undo == 0) {
return;
}
// make sure that the tab related data is up-to-date
var tabState = this._collectTabData(aTab);
this._updateTextAndScrollDataForTab(aWindow, aTab.linkedBrowser, tabState);
// store closed-tab data for undo
if (this._shouldSaveTabState(tabState)) {
let tabTitle = aTab.label;
let tabbrowser = aWindow.gBrowser;
tabTitle = this._replaceLoadingTitle(tabTitle, tabbrowser, aTab);
this._windows[aWindow.__SSi]._closedTabs.unshift({
state: tabState,
title: tabTitle,
image: tabbrowser.getIcon(aTab),
pos: aTab._tPos
});
var length = this._windows[aWindow.__SSi]._closedTabs.length;
if (length > this._max_tabs_undo)
this._windows[aWindow.__SSi]._closedTabs.splice(this._max_tabs_undo, length - this._max_tabs_undo);
}
},
/**
* When a tab loads, save state.
* @param aWindow
* Window reference
* @param aBrowser
* Browser reference
*/
onTabLoad: function(aWindow, aBrowser) {
// react on "load" and solitary "pageshow" events (the first "pageshow"
// following "load" is too late for deleting the data caches)
// It's possible to get a load event after calling stop on a browser (when
// overwriting tabs). We want to return early if the tab hasn't been restored yet.
if (aBrowser.__SS_restoreState &&
aBrowser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE) {
return;
}
delete aBrowser.__SS_data;
delete aBrowser.__SS_tabStillLoading;
delete aBrowser.__SS_formDataSaved;
this.saveStateDelayed(aWindow);
},
/**
* Called when a browser sends the "input" notification
* @param aWindow
* Window reference
* @param aBrowser
* Browser reference
*/
onTabInput: function(aWindow, aBrowser) {
// deleting __SS_formDataSaved will cause us to recollect form data
delete aBrowser.__SS_formDataSaved;
this.saveStateDelayed(aWindow, 3000);
},
/**
* When a tab is selected, save session data
* @param aWindow
* Window reference
*/
onTabSelect: function(aWindow) {
if (this._loadState == STATE_RUNNING) {
this._windows[aWindow.__SSi].selected = aWindow.gBrowser.tabContainer.selectedIndex;
let tab = aWindow.gBrowser.selectedTab;
// If __SS_restoreState is still on the browser and it is
// TAB_STATE_NEEDS_RESTORE, then then we haven't restored
// this tab yet. Explicitly call restoreTab to kick off the restore.
if (tab.linkedBrowser.__SS_restoreState &&
tab.linkedBrowser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE)
this.restoreTab(tab);
}
},
onTabShow: function(aWindow, aTab) {
// If the tab hasn't been restored yet, move it into the right bucket
if (aTab.linkedBrowser.__SS_restoreState &&
aTab.linkedBrowser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE) {
TabRestoreQueue.hiddenToVisible(aTab);
// let's kick off tab restoration again to ensure this tab gets restored
// with "restore_hidden_tabs" == false (now that it has become visible)
this.restoreNextTab();
}
// Default delay of 2 seconds gives enough time to catch multiple TabShow
// events due to changing groups in Panorama.
this.saveStateDelayed(aWindow);
},
onTabHide: function(aWindow, aTab) {
// If the tab hasn't been restored yet, move it into the right bucket
if (aTab.linkedBrowser.__SS_restoreState &&
aTab.linkedBrowser.__SS_restoreState == TAB_STATE_NEEDS_RESTORE) {
TabRestoreQueue.visibleToHidden(aTab);
}
// Default delay of 2 seconds gives enough time to catch multiple TabHide
// events due to changing groups in Panorama.
this.saveStateDelayed(aWindow);
},
/* ........ nsISessionStore API .............. */
getBrowserState: function() {
return this._toJSONString(this._getCurrentState());
},
setBrowserState: function(aState) {
this._handleClosedWindows();
try {
var state = JSON.parse(aState);
}
catch (ex) { /* invalid state object - don't restore anything */ }
if (!state || !state.windows)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
this._browserSetState = true;
// Make sure the priority queue is emptied out
this._resetRestoringState();
var window = this._getMostRecentBrowserWindow();
if (!window) {
this._restoreCount = 1;
this._openWindowWithState(state);
return;
}
// close all other browser windows
this._forEachBrowserWindow(function(aWindow) {
if (aWindow != window) {
aWindow.close();
this.onClose(aWindow);
}
});
// make sure closed window data isn't kept
this._closedWindows = [];
// determine how many windows are meant to be restored
this._restoreCount = state.windows ? state.windows.length : 0;
// restore to the given state
this.restoreWindow(window, state, true);
},
getWindowState: function(aWindow) {
if ("__SSi" in aWindow) {
return this._toJSONString(this._getWindowState(aWindow));
}
if (DyingWindowCache.has(aWindow)) {
let data = DyingWindowCache.get(aWindow);
return this._toJSONString({ windows: [data] });
}
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
},
setWindowState: function(aWindow, aState, aOverwrite) {
if (!aWindow.__SSi)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
this.restoreWindow(aWindow, aState, aOverwrite);
},
getTabState: function(aTab) {
if (!aTab.ownerDocument || !aTab.ownerDocument.defaultView.__SSi)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
var tabState = this._collectTabData(aTab);
var window = aTab.ownerDocument.defaultView;
this._updateTextAndScrollDataForTab(window, aTab.linkedBrowser, tabState);
return this._toJSONString(tabState);
},
setTabState: function(aTab, aState) {
var tabState = JSON.parse(aState);
if (!tabState.entries || !aTab.ownerDocument || !aTab.ownerDocument.defaultView.__SSi)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
var window = aTab.ownerDocument.defaultView;
this._setWindowStateBusy(window);
this.restoreHistoryPrecursor(window, [aTab], [tabState], 0, 0, 0);
},
duplicateTab: function(aWindow, aTab, aDelta) {
if (!aTab.ownerDocument || !aTab.ownerDocument.defaultView.__SSi ||
!aWindow.getBrowser)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
var tabState = this._collectTabData(aTab, true);
var sourceWindow = aTab.ownerDocument.defaultView;
this._updateTextAndScrollDataForTab(sourceWindow, aTab.linkedBrowser, tabState, true);
tabState.index += aDelta;
tabState.index = Math.max(1, Math.min(tabState.index, tabState.entries.length));
tabState.pinned = false;
this._setWindowStateBusy(aWindow);
let newTab = aTab == aWindow.gBrowser.selectedTab ?
aWindow.gBrowser.addTab(null, {relatedToCurrent: true, ownerTab: aTab}) :
aWindow.gBrowser.addTab();
this.restoreHistoryPrecursor(aWindow, [newTab], [tabState], 0, 0, 0,
true /* Load this tab right away. */);
return newTab;
},
getClosedTabCount: function(aWindow) {
if ("__SSi" in aWindow) {
return this._windows[aWindow.__SSi]._closedTabs.length;
}
if (DyingWindowCache.has(aWindow)) {
return DyingWindowCache.get(aWindow)._closedTabs.length;
}
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
},
getClosedTabData: function(aWindow) {
if ("__SSi" in aWindow) {
return this._toJSONString(this._windows[aWindow.__SSi]._closedTabs);
}
if (DyingWindowCache.has(aWindow)) {
let data = DyingWindowCache.get(aWindow);
return this._toJSONString(data._closedTabs);
}
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
},
undoCloseTab: function(aWindow, aIndex) {
if (!aWindow.__SSi)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
var closedTabs = this._windows[aWindow.__SSi]._closedTabs;
// default to the most-recently closed tab
aIndex = aIndex || 0;
if (!(aIndex in closedTabs))
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
// fetch the data of closed tab, while removing it from the array
let closedTab = closedTabs.splice(aIndex, 1).shift();
let closedTabState = closedTab.state;
this._setWindowStateBusy(aWindow);
// create a new tab
let tabbrowser = aWindow.gBrowser;
let tab = tabbrowser.addTab();
// restore tab content
this.restoreHistoryPrecursor(aWindow, [tab], [closedTabState], 1, 0, 0);
// restore the tab's position
tabbrowser.moveTabTo(tab, closedTab.pos);
// focus the tab's content area (bug 342432)
tab.linkedBrowser.focus();
return tab;
},
forgetClosedTab: function(aWindow, aIndex) {
if (!aWindow.__SSi)
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
var closedTabs = this._windows[aWindow.__SSi]._closedTabs;
// default to the most-recently closed tab
aIndex = aIndex || 0;
if (!(aIndex in closedTabs))
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
// remove closed tab from the array
closedTabs.splice(aIndex, 1);
},
getClosedWindowCount: function() {
return this._closedWindows.length;
},
getClosedWindowData: function() {
return this._toJSONString(this._closedWindows);
},
undoCloseWindow: function(aIndex) {
if (!(aIndex in this._closedWindows))
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
// reopen the window
let state = { windows: this._closedWindows.splice(aIndex, 1) };
let window = this._openWindowWithState(state);
this.windowToFocus = window;
return window;
},
forgetClosedWindow: function(aIndex) {
// default to the most-recently closed window
aIndex = aIndex || 0;
if (!(aIndex in this._closedWindows))
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
// remove closed window from the array
this._closedWindows.splice(aIndex, 1);
},
getWindowValue: function(aWindow, aKey) {
if ("__SSi" in aWindow) {
var data = this._windows[aWindow.__SSi].extData || {};
return data[aKey] || "";
}
if (DyingWindowCache.has(aWindow)) {
let data = DyingWindowCache.get(aWindow).extData || {};
return data[aKey] || "";
}
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
},
setWindowValue: function(aWindow, aKey, aStringValue) {
if (aWindow.__SSi) {
if (!this._windows[aWindow.__SSi].extData) {
this._windows[aWindow.__SSi].extData = {};
}
this._windows[aWindow.__SSi].extData[aKey] = aStringValue;
this.saveStateDelayed(aWindow);
}
else {
throw (Components.returnCode = Cr.NS_ERROR_INVALID_ARG);
}
},
deleteWindowValue: function(aWindow, aKey) {
if (aWindow.__SSi && this._windows[aWindow.__SSi].extData &&
this._windows[aWindow.__SSi].extData[aKey])
delete this._windows[aWindow.__SSi].extData[aKey];
},
getTabValue: function(aTab, aKey) {
let data = {};
if (aTab.__SS_extdata) {
data = aTab.__SS_extdata;
}
else if (aTab.linkedBrowser.__SS_data && aTab.linkedBrowser.__SS_data.extData) {
// If the tab hasn't been fully restored, get the data from the to-be-restored data
data = aTab.linkedBrowser.__SS_data.extData;
}
return data[aKey] || "";
},
setTabValue: function(aTab, aKey, aStringValue) {
// If the tab hasn't been restored, then set the data there, otherwise we
// could lose newly added data.
let saveTo;
if (aTab.__SS_extdata) {
saveTo = aTab.__SS_extdata;
}
else if (aTab.linkedBrowser.__SS_data && aTab.linkedBrowser.__SS_data.extData) {
saveTo = aTab.linkedBrowser.__SS_data.extData;
}
else {
aTab.__SS_extdata = {};
saveTo = aTab.__SS_extdata;
}
saveTo[aKey] = aStringValue;
this.saveStateDelayed(aTab.ownerDocument.defaultView);
},
deleteTabValue: function(aTab, aKey) {
// We want to make sure that if data is accessed early, we attempt to delete
// that data from __SS_data as well. Otherwise we'll throw in cases where
// data can be set or read.
let deleteFrom;
if (aTab.__SS_extdata) {
deleteFrom = aTab.__SS_extdata;
}
else if (aTab.linkedBrowser.__SS_data && aTab.linkedBrowser.__SS_data.extData) {
deleteFrom = aTab.linkedBrowser.__SS_data.extData;
}
if (deleteFrom && deleteFrom[aKey])
delete deleteFrom[aKey];
},
persistTabAttribute: function(aName) {
if (TabAttributes.persist(aName)) {
this.saveStateDelayed();
}
},
/**
* Restores the session state stored in _lastSessionState. This will attempt
* to merge data into the current session. If a window was opened at startup
* with pinned tab(s), then the remaining data from the previous session for
* that window will be opened into that winddow. Otherwise new windows will
* be opened.
*/
restoreLastSession: function() {
// Use the public getter since it also checks PB mode
if (!this.canRestoreLastSession)
throw (Components.returnCode = Cr.NS_ERROR_FAILURE);
// First collect each window with its id...
let windows = {};
this._forEachBrowserWindow(function(aWindow) {
if (aWindow.__SS_lastSessionWindowID)
windows[aWindow.__SS_lastSessionWindowID] = aWindow;
});
let lastSessionState = this._lastSessionState;
// This shouldn't ever be the case...
if (!lastSessionState.windows.length)
throw (Components.returnCode = Cr.NS_ERROR_UNEXPECTED);
// We're technically doing a restore, so set things up so we send the
// notification when we're done. We want to send "sessionstore-browser-state-restored".
this._restoreCount = lastSessionState.windows.length;
this._browserSetState = true;
// We want to re-use the last opened window instead of opening a new one in
// the case where it's "empty" and not associated with a window in the session.
// We will do more processing via _prepWindowToRestoreInto if we need to use
// the lastWindow.
let lastWindow = this._getMostRecentBrowserWindow();
let canUseLastWindow = lastWindow &&
!lastWindow.__SS_lastSessionWindowID;
// Restore into windows or open new ones as needed.
for (let i = 0; i < lastSessionState.windows.length; i++) {
let winState = lastSessionState.windows[i];
let lastSessionWindowID = winState.__lastSessionWindowID;
// delete lastSessionWindowID so we don't add that to the window again
delete winState.__lastSessionWindowID;
// See if we can use an open window. First try one that is associated with
// the state we're trying to restore and then fallback to the last selected
// window.
let windowToUse = windows[lastSessionWindowID];
if (!windowToUse && canUseLastWindow) {
windowToUse = lastWindow;
canUseLastWindow = false;
}
let [canUseWindow, canOverwriteTabs] = this._prepWindowToRestoreInto(windowToUse);
// If there's a window already open that we can restore into, use that
if (canUseWindow) {
// Since we're not overwriting existing tabs, we want to merge _closedTabs,
// putting existing ones first. Then make sure we're respecting the max pref.
if (winState._closedTabs && winState._closedTabs.length) {
let curWinState = this._windows[windowToUse.__SSi];
curWinState._closedTabs = curWinState._closedTabs.concat(winState._closedTabs);
curWinState._closedTabs.splice(this._prefBranch.getIntPref("sessionstore.max_tabs_undo"), curWinState._closedTabs.length);
}
// Restore into that window - pretend it's a followup since we'll already
// have a focused window.
//XXXzpao This is going to merge extData together (taking what was in
// winState over what is in the window already. The hack we have
// in _preWindowToRestoreInto will prevent most (all?) Panorama
// weirdness but we will still merge other extData.
// Bug 588217 should make this go away by merging the group data.
this.restoreWindow(windowToUse, { windows: [winState] }, canOverwriteTabs, true);
}
else {
this._openWindowWithState({ windows: [winState] });
}
}
// Merge closed windows from this session with ones from last session
if (lastSessionState._closedWindows) {
this._closedWindows = this._closedWindows.concat(lastSessionState._closedWindows);
this._capClosedWindows();
}
#ifdef MOZ_DEVTOOLS
// Scratchpad
if (lastSessionState.scratchpads) {
ScratchpadManager.restoreSession(lastSessionState.scratchpads);
}
// The Browser Console
if (lastSessionState.browserConsole) {
HUDService.restoreBrowserConsoleSession();
}
#endif
// Set data that persists between sessions
this._recentCrashes = lastSessionState.session &&
lastSessionState.session.recentCrashes || 0;
this._sessionStartTime = lastSessionState.session &&
lastSessionState.session.startTime ||
this._sessionStartTime;
this._lastSessionState = null;
},
/**
* See if aWindow is usable for use when restoring a previous session via
* restoreLastSession. If usable, prepare it for use.
*
* @param aWindow
* the window to inspect & prepare
* @returns [canUseWindow, canOverwriteTabs]
* canUseWindow: can the window be used to restore into
* canOverwriteTabs: all of the current tabs are home pages and we
* can overwrite them
*/
_prepWindowToRestoreInto: function(aWindow) {
if (!aWindow)
return [false, false];
let event = aWindow.document.createEvent("Events");
event.initEvent("SSRestoreIntoWindow", true, true);
// Check if we can use the window.
if (!aWindow.dispatchEvent(event))
return [false, false];
// We might be able to overwrite the existing tabs instead of just adding
// the previous session's tabs to the end. This will be set if possible.
let canOverwriteTabs = false;
// Look at the open tabs in comparison to home pages. If all the tabs are
// home pages then we'll end up overwriting all of them. Otherwise we'll
// just close the tabs that match home pages. Tabs with the about:blank
// URI will always be overwritten.
let homePages = ["about:blank"];
let removableTabs = [];
let tabbrowser = aWindow.gBrowser;
let normalTabsLen = tabbrowser.tabs.length - tabbrowser._numPinnedTabs;
let startupPref = this._prefBranch.getIntPref("startup.page");
if (startupPref == 1)
homePages = homePages.concat(aWindow.gHomeButton.getHomePage().split("|"));
for (let i = tabbrowser._numPinnedTabs; i < tabbrowser.tabs.length; i++) {
let tab = tabbrowser.tabs[i];
if (homePages.indexOf(tab.linkedBrowser.currentURI.spec) != -1) {
removableTabs.push(tab);
}
}
if (tabbrowser.tabs.length == removableTabs.length) {
canOverwriteTabs = true;
}
else {
// If we're not overwriting all of the tabs, then close the home tabs.
for (let i = removableTabs.length - 1; i >= 0; i--) {
tabbrowser.removeTab(removableTabs.pop(), { animate: false });
}
}
return [true, canOverwriteTabs];
},
/* ........ Saving Functionality .............. */
/**
* Store all session data for a window
* @param aWindow
* Window reference
*/
_saveWindowHistory: function(aWindow) {
var tabbrowser = aWindow.gBrowser;
var tabs = tabbrowser.tabs;
var tabsData = this._windows[aWindow.__SSi].tabs = [];
for (var i = 0; i < tabs.length; i++)
tabsData.push(this._collectTabData(tabs[i]));
this._windows[aWindow.__SSi].selected = tabbrowser.mTabBox.selectedIndex + 1;
},
/**
* Collect data related to a single tab
* @param aTab
* tabbrowser tab
* @param aFullData
* always return privacy sensitive data (use with care)
* @returns object
*/
_collectTabData: function(aTab, aFullData) {
var tabData = { entries: [], lastAccessed: aTab.lastAccessed };
var browser = aTab.linkedBrowser;
if (!browser || !browser.currentURI)
// can happen when calling this function right after .addTab()
return tabData;
else if (browser.__SS_data && browser.__SS_tabStillLoading) {
// use the data to be restored when the tab hasn't been completely loaded
tabData = browser.__SS_data;
if (aTab.pinned)
tabData.pinned = true;
else
delete tabData.pinned;
tabData.hidden = aTab.hidden;
// If __SS_extdata is set then we'll use that since it might be newer.
if (aTab.__SS_extdata)
tabData.extData = aTab.__SS_extdata;
// If it exists but is empty then a key was likely deleted. In that case just
// delete extData.
if (tabData.extData && !Object.keys(tabData.extData).length)
delete tabData.extData;
return tabData;
}
var history = null;
try {
history = browser.sessionHistory;
}
catch (ex) { } // this could happen if we catch a tab during (de)initialization
// Limit number of back/forward button history entries to save
let oldest, newest;
let maxSerializeBack = this._prefBranch.getIntPref("sessionstore.max_serialize_back");
if (maxSerializeBack >= 0) {
oldest = Math.max(0, history.index - maxSerializeBack);
} else { // History.getEntryAtIndex(0, ...) is the oldest.
oldest = 0;
}
let maxSerializeFwd = this._prefBranch.getIntPref("sessionstore.max_serialize_forward");
if (maxSerializeFwd >= 0) {
newest = Math.min(history.count - 1, history.index + maxSerializeFwd);
} else { // History.getEntryAtIndex(history.count - 1, ...) is the newest.
newest = history.count - 1;
}
// XXXzeniko anchor navigation doesn't reset __SS_data, so we could reuse
// data even when we shouldn't (e.g. Back, different anchor)
// Warning: this is required to save form data and scrolling position!
if (history && browser.__SS_data &&
browser.__SS_data.entries[history.index] &&
browser.__SS_data.entries[history.index].url == browser.currentURI.spec &&
history.index < this._sessionhistory_max_entries - 1 && !aFullData) {
try {
tabData.entries = browser.__SS_data.entries.slice(oldest, newest + 1);
}
catch (ex) {
// No errors are expected above, but we use try-catch to keep sessionstore.js safe
NS_ASSERT(false, "SessionStore failed to slice history from browser.__SS_data");
}
// Set the one-based index of the currently active tab, ensuring it isn't out of bounds
tabData.index = Math.min(history.index - oldest + 1, tabData.entries.length);
}
else if (history && history.count > 0) {
browser.__SS_hostSchemeData = [];
try {
for (var j = oldest; j <= newest; j++) {
let entry = this._serializeHistoryEntry(history.getEntryAtIndex(j, false),
aFullData, aTab.pinned, browser.__SS_hostSchemeData);
tabData.entries.push(entry);
}
}
catch (ex) {
// In some cases, getEntryAtIndex will throw. This seems to be due to
// history.count being higher than it should be. By doing this in a
// try-catch, we'll update history to where it breaks, assert for
// non-release builds, and still save sessionstore.js.
NS_ASSERT(false, "SessionStore failed gathering complete history " +
"for the focused window/tab. See bug 669196.");
}
// Set the one-based index of the currently active tab, ensuring it isn't out of bounds
tabData.index = Math.min(history.index - oldest + 1, tabData.entries.length);
// make sure not to cache privacy sensitive data which shouldn't get out
if (!aFullData)
browser.__SS_data = tabData;
}
else if (browser.currentURI.spec != "about:blank" ||
browser.contentDocument.body.hasChildNodes()) {
tabData.entries[0] = { url: browser.currentURI.spec };
tabData.index = 1;
}
// If there is a userTypedValue set, then either the user has typed something
// in the URL bar, or a new tab was opened with a URI to load. userTypedClear
// is used to indicate whether the tab was in some sort of loading state with
// userTypedValue.
if (browser.userTypedValue) {
tabData.userTypedValue = browser.userTypedValue;
// We always used to keep track of the loading state as an integer, where
// '0' indicated the user had typed since the last load (or no load was
// ongoing), and any positive value indicated we had started a load since
// the last time the user typed in the URL bar. Mimic this to keep the
// session store representation in sync, even though we now represent this
// more explicitly:
tabData.userTypedClear = browser.didStartLoadSinceLastUserTyping() ? 1 : 0;
} else {
delete tabData.userTypedValue;
delete tabData.userTypedClear;
}
if (aTab.pinned)
tabData.pinned = true;
else
delete tabData.pinned;
tabData.hidden = aTab.hidden;
var disallow = [];
for (let cap of gDocShellCapabilities(browser.docShell))
if (!browser.docShell["allow" + cap])
disallow.push(cap);
if (disallow.length > 0)
tabData.disallow = disallow.join(",");
else if (tabData.disallow)
delete tabData.disallow;
// Save tab attributes.
tabData.attributes = TabAttributes.get(aTab);
// Store the tab icon.
let tabbrowser = aTab.ownerDocument.defaultView.gBrowser;
tabData.image = tabbrowser.getIcon(aTab);
if (aTab.__SS_extdata)
tabData.extData = aTab.__SS_extdata;
else if (tabData.extData)
delete tabData.extData;
if (history && browser.docShell instanceof Ci.nsIDocShell) {
let storageData = SessionStorage.serialize(browser.docShell, aFullData)
if (Object.keys(storageData).length)
tabData.storage = storageData;
}
return tabData;
},
/**
* Get an object that is a serialized representation of a History entry
* Used for data storage
* @param aEntry
* nsISHEntry instance
* @param aFullData
* always return privacy sensitive data (use with care)
* @param aIsPinned
* the tab is pinned and should be treated differently for privacy
* @param aHostSchemeData
* an array of objects with host & scheme keys
* @returns object
*/
_serializeHistoryEntry:
function(aEntry, aFullData, aIsPinned, aHostSchemeData) {
var entry = { url: aEntry.URI.spec };
try {
// throwing is expensive, we know that about: pages will throw
if (entry.url.indexOf("about:") != 0)
aHostSchemeData.push({ host: aEntry.URI.host, scheme: aEntry.URI.scheme });
}
catch (ex) {
// We just won't attempt to get cookies for this entry.
}
if (aEntry.title && aEntry.title != entry.url) {
entry.title = aEntry.title;
}
if (aEntry.isSubFrame) {
entry.subframe = true;
}
if (!(aEntry instanceof Ci.nsISHEntry)) {
return entry;
}
var cacheKey = aEntry.cacheKey;
if (cacheKey && cacheKey instanceof Ci.nsISupportsPRUint32 &&
cacheKey.data != 0) {
// XXXbz would be better to have cache keys implement
// nsISerializable or something.
entry.cacheKey = cacheKey.data;
}
entry.ID = aEntry.ID;
entry.docshellID = aEntry.docshellID;
if (aEntry.referrerURI)
entry.referrer = aEntry.referrerURI.spec;
if (aEntry.srcdocData)
entry.srcdocData = aEntry.srcdocData;
if (aEntry.isSrcdocEntry)
entry.isSrcdocEntry = aEntry.isSrcdocEntry;
if (aEntry.contentType)
entry.contentType = aEntry.contentType;
var x = {}, y = {};
aEntry.getScrollPosition(x, y);
if (x.value != 0 || y.value != 0)
entry.scroll = x.value + "," + y.value;
try {
var prefPostdata = this._prefBranch.getIntPref("sessionstore.postdata");
if (aEntry.postData && (aFullData || prefPostdata &&
this.checkPrivacyLevel(aEntry.URI.schemeIs("https"), aIsPinned))) {
aEntry.postData.QueryInterface(Ci.nsISeekableStream).
seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
var stream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream);
stream.setInputStream(aEntry.postData);
var postBytes = stream.readByteArray(stream.available());
var postdata = String.fromCharCode.apply(null, postBytes);
if (aFullData || prefPostdata == -1 ||
postdata.replace(/^(Content-.*\r\n)+(\r\n)*/, "").length <=
prefPostdata) {
// We can stop doing base64 encoding once our serialization into JSON
// is guaranteed to handle all chars in strings, including embedded
// nulls.
entry.postdata_b64 = btoa(postdata);
}
}
}
catch (ex) { debug(ex); } // POSTDATA is tricky - especially since some extensions don't get it right
if (aEntry.triggeringPrincipal) {
// Not catching anything specific here, just possible errors
// from writeCompoundObject and the like.
try {
var binaryStream = Cc["@mozilla.org/binaryoutputstream;1"].
createInstance(Ci.nsIObjectOutputStream);
var pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
pipe.init(false, false, 0, 0xffffffff, null);
binaryStream.setOutputStream(pipe.outputStream);
binaryStream.writeCompoundObject(aEntry.triggeringPrincipal, Ci.nsIPrincipal, true);
binaryStream.close();
// Now we want to read the data from the pipe's input end and encode it.
var scriptableStream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream);
scriptableStream.setInputStream(pipe.inputStream);
var triggeringPrincipalBytes =
scriptableStream.readByteArray(scriptableStream.available());
// We can stop doing base64 encoding once our serialization into JSON
// is guaranteed to handle all chars in strings, including embedded
// nulls.
entry.triggeringPrincipal_b64 = btoa(String.fromCharCode.apply(null, triggeringPrincipalBytes));
}
catch (ex) { debug(ex); }
}
entry.docIdentifier = aEntry.BFCacheEntry.ID;
if (aEntry.stateData != null) {
entry.structuredCloneState = aEntry.stateData.getDataAsBase64();
entry.structuredCloneVersion = aEntry.stateData.formatVersion;
}
if (!(aEntry instanceof Ci.nsISHContainer)) {
return entry;
}
if (aEntry.childCount > 0) {
let children = [];
for (var i = 0; i < aEntry.childCount; i++) {
var child = aEntry.GetChildAt(i);
if (child) {
// don't try to restore framesets containing wyciwyg URLs (cf. bug 424689 and bug 450595)
if (child.URI.schemeIs("wyciwyg")) {
children = [];
break;
}
children.push(this._serializeHistoryEntry(child, aFullData,
aIsPinned, aHostSchemeData));
}
}
if (children.length)
entry.children = children;
}
return entry;
},
/**
* go through all tabs and store the current scroll positions
* and innerHTML content of WYSIWYG editors
* @param aWindow
* Window reference
*/
_updateTextAndScrollData: function(aWindow) {
var browsers = aWindow.gBrowser.browsers;
this._windows[aWindow.__SSi].tabs.forEach(function(tabData, i) {
try {
this._updateTextAndScrollDataForTab(aWindow, browsers[i], tabData);
}
catch (ex) { debug(ex); } // get as much data as possible, ignore failures (might succeed the next time)
}, this);
},
/**
* go through all frames and store the current scroll positions
* and innerHTML content of WYSIWYG editors
* @param aWindow
* Window reference
* @param aBrowser
* single browser reference
* @param aTabData
* tabData object to add the information to
* @param aFullData
* always return privacy sensitive data (use with care)
*/
_updateTextAndScrollDataForTab:
function(aWindow, aBrowser, aTabData, aFullData) {
// we shouldn't update data for incompletely initialized tabs
if (aBrowser.__SS_data && aBrowser.__SS_tabStillLoading)
return;
var tabIndex = (aTabData.index || aTabData.entries.length) - 1;
// entry data needn't exist for tabs just initialized with an incomplete session state
if (!aTabData.entries[tabIndex])
return;
let selectedPageStyle = aBrowser.markupDocumentViewer.authorStyleDisabled ? "_nostyle" :
this._getSelectedPageStyle(aBrowser.contentWindow);
if (selectedPageStyle)
aTabData.pageStyle = selectedPageStyle;
else if (aTabData.pageStyle)
delete aTabData.pageStyle;
this._updateTextAndScrollDataForFrame(aWindow, aBrowser.contentWindow,
aTabData.entries[tabIndex],
!aBrowser.__SS_formDataSaved, aFullData,
!!aTabData.pinned);
aBrowser.__SS_formDataSaved = true;
if (aBrowser.currentURI.spec == "about:config")
aTabData.entries[tabIndex].formdata = {
id: {
"textbox": aBrowser.contentDocument.getElementById("textbox").value
},
xpath: {}
};
},
/**
* go through all subframes and store all form data, the current
* scroll positions and innerHTML content of WYSIWYG editors
* @param aWindow
* Window reference
* @param aContent
* frame reference
* @param aData
* part of a tabData object to add the information to
* @param aUpdateFormData
* update all form data for this tab
* @param aFullData
* always return privacy sensitive data (use with care)
* @param aIsPinned
* the tab is pinned and should be treated differently for privacy
*/
_updateTextAndScrollDataForFrame:
function(aWindow, aContent, aData,
aUpdateFormData, aFullData, aIsPinned) {
for (var i = 0; i < aContent.frames.length; i++) {
if (aData.children && aData.children[i])
this._updateTextAndScrollDataForFrame(aWindow, aContent.frames[i],
aData.children[i], aUpdateFormData,
aFullData, aIsPinned);
}
var isHTTPS = this._getURIFromString((aContent.parent || aContent).
document.location.href).schemeIs("https");
let isAboutSR = aContent.top.document.location.href == "about:sessionrestore";
if (aFullData || this.checkPrivacyLevel(isHTTPS, aIsPinned) || isAboutSR) {
if (aFullData || aUpdateFormData) {
let formData = DocumentUtils.getFormData(aContent.document);
// We want to avoid saving data for about:sessionrestore as a string.
// Since it's stored in the form as stringified JSON, stringifying further
// causes an explosion of escape characters. cf. bug 467409
if (formData && isAboutSR) {
formData.id["sessionData"] = JSON.parse(formData.id["sessionData"]);
}
if (Object.keys(formData.id).length ||
Object.keys(formData.xpath).length) {
aData.formdata = formData;
} else if (aData.formdata) {
delete aData.formdata;
}
}
// designMode is undefined e.g. for XUL documents (as about:config)
if ((aContent.document.designMode || "") == "on" && aContent.document.body)
aData.innerHTML = aContent.document.body.innerHTML;
}
// get scroll position from nsIDOMWindowUtils, since it allows avoiding a
// flush of layout
let domWindowUtils = aContent.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
let scrollX = {}, scrollY = {};
domWindowUtils.getScrollXY(false, scrollX, scrollY);
aData.scroll = scrollX.value + "," + scrollY.value;
},
/**
* determine the title of the currently enabled style sheet (if any)
* and recurse through the frameset if necessary
* @param aContent is a frame reference
* @returns the title style sheet determined to be enabled (empty string if none)
*/
_getSelectedPageStyle: function(aContent) {
const forScreen = /(?:^|,)\s*(?:all|screen)\s*(?:,|$)/i;
for (let i = 0; i < aContent.document.styleSheets.length; i++) {
let ss = aContent.document.styleSheets[i];
let media = ss.media.mediaText;
if (!ss.disabled && ss.title && (!media || forScreen.test(media)))
return ss.title
}
for (let i = 0; i < aContent.frames.length; i++) {
let selectedPageStyle = this._getSelectedPageStyle(aContent.frames[i]);
if (selectedPageStyle)
return selectedPageStyle;
}
return "";
},
/**
* extract the base domain from a history entry and its children
* @param aEntry
* the history entry, serialized
* @param aHosts
* the hash that will be used to store hosts eg, { hostname: true }
* @param aCheckPrivacy
* should we check the privacy level for https
* @param aIsPinned
* is the entry we're evaluating for a pinned tab; used only if
* aCheckPrivacy
*/
_extractHostsForCookiesFromEntry:
function(aEntry, aHosts, aCheckPrivacy, aIsPinned) {
let host = aEntry._host,
scheme = aEntry._scheme;
// If host & scheme aren't defined, then we are likely here in the startup
// process via _splitCookiesFromWindow. In that case, we'll turn aEntry.url
// into an nsIURI and get host/scheme from that. This will throw for about:
// urls in which case we don't need to do anything.
if (!host && !scheme) {
try {
let uri = this._getURIFromString(aEntry.url);
host = uri.host;
scheme = uri.scheme;
this._extractHostsForCookiesFromHostScheme(host, scheme, aHosts, aCheckPrivacy, aIsPinned);
}
catch(ex) { }
}
if (aEntry.children) {
aEntry.children.forEach(function(entry) {
this._extractHostsForCookiesFromEntry(entry, aHosts, aCheckPrivacy, aIsPinned);
}, this);
}
},
/**
* extract the base domain from a host & scheme
* @param aHost
* the host of a uri (usually via nsIURI.host)
* @param aScheme
* the scheme of a uri (usually via nsIURI.scheme)
* @param aHosts
* the hash that will be used to store hosts eg, { hostname: true }
* @param aCheckPrivacy
* should we check the privacy level for https
* @param aIsPinned
* is the entry we're evaluating for a pinned tab; used only if
* aCheckPrivacy
*/
_extractHostsForCookiesFromHostScheme:
function(aHost, aScheme, aHosts, aCheckPrivacy, aIsPinned) {
// host and scheme may not be set (for about: urls for example), in which
// case testing scheme will be sufficient.
if (/https?/.test(aScheme) && !aHosts[aHost] &&
(!aCheckPrivacy ||
this.checkPrivacyLevel(aScheme == "https", aIsPinned))) {
// By setting this to true or false, we can determine when looking at
// the host in _updateCookies if we should check for privacy.
aHosts[aHost] = aIsPinned;
}
else if (aScheme == "file") {
aHosts[aHost] = true;
}
},
/**
* store all hosts for a URL
* @param aWindow
* Window reference
*/
_updateCookieHosts: function(aWindow) {
var hosts = this._internalWindows[aWindow.__SSi].hosts = {};
// Since _updateCookiesHosts is only ever called for open windows during a
// session, we can call into _extractHostsForCookiesFromHostScheme directly
// using data that is attached to each browser.
for (let i = 0; i < aWindow.gBrowser.tabs.length; i++) {
let tab = aWindow.gBrowser.tabs[i];
let hostSchemeData = tab.linkedBrowser.__SS_hostSchemeData || [];
for (let j = 0; j < hostSchemeData.length; j++) {
this._extractHostsForCookiesFromHostScheme(hostSchemeData[j].host,
hostSchemeData[j].scheme,
hosts, true, tab.pinned);
}
}
},
/**
* Serialize cookie data
* @param aWindows
* JS object containing window data references
* { id: winData, etc. }
*/
_updateCookies: function(aWindows) {
function addCookieToHash(aHash, aHost, aPath, aName, aCookie) {
// lazily build up a 3-dimensional hash, with
// aHost, aPath, and aName as keys
if (!aHash[aHost])
aHash[aHost] = {};
if (!aHash[aHost][aPath])
aHash[aHost][aPath] = {};
aHash[aHost][aPath][aName] = aCookie;
}
var jscookies = {};
var _this = this;
// MAX_EXPIRY should be 2^63-1, but JavaScript can't handle that precision
var MAX_EXPIRY = Math.pow(2, 62);
for (let [id, window] in Iterator(aWindows)) {
window.cookies = [];
let internalWindow = this._internalWindows[id];
if (!internalWindow.hosts)
return;
for (var [host, isPinned] in Iterator(internalWindow.hosts)) {
let list;
try {
list = Services.cookies.getCookiesFromHost(host, {});
}
catch (ex) {
debug("getCookiesFromHost failed. Host: " + host);
}
while (list && list.hasMoreElements()) {
var cookie = list.getNext().QueryInterface(Ci.nsICookie2);
// window._hosts will only have hosts with the right privacy rules,
// so there is no need to do anything special with this call to
// checkPrivacyLevel.
if (cookie.isSession && _this.checkPrivacyLevel(cookie.isSecure, isPinned)) {
// use the cookie's host, path, and name as keys into a hash,
// to make sure we serialize each cookie only once
if (!(cookie.host in jscookies &&
cookie.path in jscookies[cookie.host] &&
cookie.name in jscookies[cookie.host][cookie.path])) {
var jscookie = { "host": cookie.host, "value": cookie.value