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.

2299 lines
70 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. µBlock - a browser extension to block requests.
  3. Copyright (C) 2014 The µBlock authors
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see {http://www.gnu.org/licenses/}.
  14. Home: https://github.com/gorhill/uMatrix
  15. */
  16. /* jshint bitwise: false, boss: true, esnext: true */
  17. /* global self, Components, punycode, µBlock */
  18. // For background page
  19. /******************************************************************************/
  20. (function() {
  21. 'use strict';
  22. /******************************************************************************/
  23. // Useful links
  24. //
  25. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface
  26. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm
  27. /******************************************************************************/
  28. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  29. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  30. /******************************************************************************/
  31. var vAPI = self.vAPI = self.vAPI || {};
  32. vAPI.firefox = true;
  33. /******************************************************************************/
  34. vAPI.app = {
  35. name: 'uMatrix',
  36. version: location.hash.slice(1)
  37. };
  38. /******************************************************************************/
  39. vAPI.app.start = function() {
  40. };
  41. /******************************************************************************/
  42. vAPI.app.stop = function() {
  43. };
  44. /******************************************************************************/
  45. vAPI.app.restart = function() {
  46. // Listening in bootstrap.js
  47. Cc['@mozilla.org/childprocessmessagemanager;1']
  48. .getService(Ci.nsIMessageSender)
  49. .sendAsyncMessage(location.host + '-restart');
  50. };
  51. /******************************************************************************/
  52. // https://stackoverflow.com/questions/6715571/how-to-get-result-of-console-trace-as-string-in-javascript-with-chrome-or-fire/28118170#28118170
  53. /*
  54. function logStackTrace(msg) {
  55. var stack;
  56. try {
  57. throw new Error('');
  58. }
  59. catch (error) {
  60. stack = error.stack || '';
  61. }
  62. stack = stack.split('\n').map(function(line) { return line.trim(); });
  63. stack.shift();
  64. if ( msg ) {
  65. stack.unshift(msg);
  66. }
  67. console.log(stack.join('\n'));
  68. }
  69. */
  70. /******************************************************************************/
  71. // List of things that needs to be destroyed when disabling the extension
  72. // Only functions should be added to it
  73. var cleanupTasks = [];
  74. // This must be updated manually, every time a new task is added/removed
  75. // Fixed by github.com/AlexVallat:
  76. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  77. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  78. var expectedNumberOfCleanups = 7;
  79. window.addEventListener('unload', function() {
  80. for ( var cleanup of cleanupTasks ) {
  81. cleanup();
  82. }
  83. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  84. console.error(
  85. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  86. cleanupTasks.length,
  87. expectedNumberOfCleanups
  88. );
  89. }
  90. // frameModule needs to be cleared too
  91. var frameModule = {};
  92. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  93. frameModule.contentObserver.unregister();
  94. Cu.unload(vAPI.getURL('frameModule.js'));
  95. });
  96. /******************************************************************************/
  97. vAPI.browserSettings = {
  98. setBool: function(branch, setting, value) {
  99. try {
  100. Services.prefs
  101. .getBranch(branch + '.')
  102. .setBoolPref(setting, value);
  103. } catch (ex) {
  104. }
  105. },
  106. set: function(details) {
  107. for ( var setting in details ) {
  108. if ( details.hasOwnProperty(setting) === false ) {
  109. continue;
  110. }
  111. switch ( setting ) {
  112. case 'prefetching':
  113. this.setBool('network', 'prefetch-next', !!details[setting]);
  114. break;
  115. case 'hyperlinkAuditing':
  116. this.setBool('browser', 'send_pings', !!details[setting]);
  117. this.setBool('beacon', 'enabled', !!details[setting]);
  118. break;
  119. default:
  120. break;
  121. }
  122. }
  123. }
  124. };
  125. /******************************************************************************/
  126. // API matches that of chrome.storage.local:
  127. // https://developer.chrome.com/extensions/storage
  128. vAPI.storage = (function() {
  129. var db = null;
  130. var vacuumTimer = null;
  131. var close = function() {
  132. if ( vacuumTimer !== null ) {
  133. clearTimeout(vacuumTimer);
  134. vacuumTimer = null;
  135. }
  136. if ( db === null ) {
  137. return;
  138. }
  139. db.asyncClose();
  140. db = null;
  141. };
  142. var open = function() {
  143. if ( db !== null ) {
  144. return db;
  145. }
  146. // Create path
  147. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  148. path.append('extension-data');
  149. if ( !path.exists() ) {
  150. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  151. }
  152. if ( !path.isDirectory() ) {
  153. throw Error('Should be a directory...');
  154. }
  155. path.append(location.host + '.sqlite');
  156. // Open database
  157. try {
  158. db = Services.storage.openDatabase(path);
  159. if ( db.connectionReady === false ) {
  160. db.asyncClose();
  161. db = null;
  162. }
  163. } catch (ex) {
  164. }
  165. if ( db === null ) {
  166. return null;
  167. }
  168. // Database was opened, register cleanup task
  169. cleanupTasks.push(close);
  170. // Setup database
  171. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
  172. .executeAsync();
  173. if ( vacuum !== null ) {
  174. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  175. }
  176. return db;
  177. };
  178. // https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
  179. // Vacuum only once, and only while idle
  180. var vacuum = function() {
  181. vacuumTimer = null;
  182. if ( db === null ) {
  183. return;
  184. }
  185. var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
  186. .getService(Ci.nsIIdleService);
  187. if ( idleSvc.idleTime < 60000 ) {
  188. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  189. return;
  190. }
  191. db.createAsyncStatement('VACUUM').executeAsync();
  192. vacuum = null;
  193. };
  194. // Execute a query
  195. var runStatement = function(stmt, callback) {
  196. var result = {};
  197. stmt.executeAsync({
  198. handleResult: function(rows) {
  199. if ( !rows || typeof callback !== 'function' ) {
  200. return;
  201. }
  202. var row;
  203. while ( row = rows.getNextRow() ) {
  204. // we assume that there will be two columns, since we're
  205. // using it only for preferences
  206. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  207. }
  208. },
  209. handleCompletion: function(reason) {
  210. if ( typeof callback === 'function' && reason === 0 ) {
  211. callback(result);
  212. }
  213. },
  214. handleError: function(error) {
  215. console.error('SQLite error ', error.result, error.message);
  216. // Caller expects an answer regardless of failure.
  217. if ( typeof callback === 'function' ) {
  218. callback(null);
  219. }
  220. }
  221. });
  222. };
  223. var bindNames = function(stmt, names) {
  224. if ( Array.isArray(names) === false || names.length === 0 ) {
  225. return;
  226. }
  227. var params = stmt.newBindingParamsArray();
  228. var i = names.length, bp;
  229. while ( i-- ) {
  230. bp = params.newBindingParams();
  231. bp.bindByName('name', names[i]);
  232. params.addParams(bp);
  233. }
  234. stmt.bindParameters(params);
  235. };
  236. var clear = function(callback) {
  237. if ( open() === null ) {
  238. if ( typeof callback === 'function' ) {
  239. callback();
  240. }
  241. return;
  242. }
  243. runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
  244. };
  245. var getBytesInUse = function(keys, callback) {
  246. if ( typeof callback !== 'function' ) {
  247. return;
  248. }
  249. if ( open() === null ) {
  250. callback(0);
  251. return;
  252. }
  253. var stmt;
  254. if ( Array.isArray(keys) ) {
  255. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
  256. bindNames(keys);
  257. } else {
  258. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
  259. }
  260. runStatement(stmt, function(result) {
  261. callback(result.size);
  262. });
  263. };
  264. var read = function(details, callback) {
  265. if ( typeof callback !== 'function' ) {
  266. return;
  267. }
  268. var prepareResult = function(result) {
  269. var key;
  270. for ( key in result ) {
  271. if ( result.hasOwnProperty(key) === false ) {
  272. continue;
  273. }
  274. result[key] = JSON.parse(result[key]);
  275. }
  276. if ( typeof details === 'object' && details !== null ) {
  277. for ( key in details ) {
  278. if ( result.hasOwnProperty(key) === false ) {
  279. result[key] = details[key];
  280. }
  281. }
  282. }
  283. callback(result);
  284. };
  285. if ( open() === null ) {
  286. prepareResult({});
  287. return;
  288. }
  289. var names = [];
  290. if ( details !== null ) {
  291. if ( Array.isArray(details) ) {
  292. names = details;
  293. } else if ( typeof details === 'object' ) {
  294. names = Object.keys(details);
  295. } else {
  296. names = [details.toString()];
  297. }
  298. }
  299. var stmt;
  300. if ( names.length === 0 ) {
  301. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  302. } else {
  303. stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
  304. bindNames(stmt, names);
  305. }
  306. runStatement(stmt, prepareResult);
  307. };
  308. var remove = function(keys, callback) {
  309. if ( open() === null ) {
  310. if ( typeof callback === 'function' ) {
  311. callback();
  312. }
  313. return;
  314. }
  315. var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
  316. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  317. runStatement(stmt, callback);
  318. };
  319. var write = function(details, callback) {
  320. if ( open() === null ) {
  321. if ( typeof callback === 'function' ) {
  322. callback();
  323. }
  324. return;
  325. }
  326. var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
  327. var params = stmt.newBindingParamsArray(), bp;
  328. for ( var key in details ) {
  329. if ( details.hasOwnProperty(key) === false ) {
  330. continue;
  331. }
  332. bp = params.newBindingParams();
  333. bp.bindByName('name', key);
  334. bp.bindByName('value', JSON.stringify(details[key]));
  335. params.addParams(bp);
  336. }
  337. if ( params.length === 0 ) {
  338. return;
  339. }
  340. stmt.bindParameters(params);
  341. runStatement(stmt, callback);
  342. };
  343. // Export API
  344. var api = {
  345. QUOTA_BYTES: 100 * 1024 * 1024,
  346. clear: clear,
  347. get: read,
  348. getBytesInUse: getBytesInUse,
  349. remove: remove,
  350. set: write
  351. };
  352. return api;
  353. })();
  354. /******************************************************************************/
  355. var getTabBrowser = function(win) {
  356. return win.gBrowser || null;
  357. };
  358. /******************************************************************************/
  359. var getOwnerWindow = function(target) {
  360. if ( target.ownerDocument ) {
  361. return target.ownerDocument.defaultView;
  362. }
  363. return null;
  364. };
  365. /******************************************************************************/
  366. vAPI.isBehindTheSceneTabId = function(tabId) {
  367. return tabId.toString() === '-1';
  368. };
  369. vAPI.noTabId = '-1';
  370. /******************************************************************************/
  371. vAPI.tabs = {};
  372. /******************************************************************************/
  373. vAPI.tabs.registerListeners = function() {
  374. tabWatcher.start();
  375. };
  376. /******************************************************************************/
  377. vAPI.tabs.get = function(tabId, callback) {
  378. var browser;
  379. if ( tabId === null ) {
  380. browser = tabWatcher.currentBrowser();
  381. tabId = tabWatcher.tabIdFromTarget(browser);
  382. } else {
  383. browser = tabWatcher.browserFromTabId(tabId);
  384. }
  385. // For internal use
  386. if ( typeof callback !== 'function' ) {
  387. return browser;
  388. }
  389. if ( !browser ) {
  390. callback();
  391. return;
  392. }
  393. var win = getOwnerWindow(browser);
  394. var tabBrowser = getTabBrowser(win);
  395. var windows = this.getWindows();
  396. callback({
  397. id: tabId,
  398. index: tabWatcher.indexFromTarget(browser),
  399. windowId: windows.indexOf(win),
  400. active: browser === tabBrowser.selectedBrowser,
  401. url: browser.currentURI.asciiSpec,
  402. title: browser.contentTitle
  403. });
  404. };
  405. /******************************************************************************/
  406. vAPI.tabs.getAllSync = function(window) {
  407. var win, tab;
  408. var tabs = [];
  409. for ( win of this.getWindows() ) {
  410. if ( window && window !== win ) {
  411. continue;
  412. }
  413. var tabBrowser = getTabBrowser(win);
  414. if ( tabBrowser === null ) {
  415. continue;
  416. }
  417. for ( tab of tabBrowser.tabs ) {
  418. tabs.push(tab);
  419. }
  420. }
  421. return tabs;
  422. };
  423. /******************************************************************************/
  424. vAPI.tabs.getAll = function(callback) {
  425. var tabs = [], tab;
  426. for ( var browser of tabWatcher.browsers() ) {
  427. tab = tabWatcher.tabFromBrowser(browser);
  428. if ( tab === null ) {
  429. continue;
  430. }
  431. if ( tab.hasAttribute('pending') ) {
  432. continue;
  433. }
  434. tabs.push({
  435. id: tabWatcher.tabIdFromTarget(browser),
  436. url: browser.currentURI.asciiSpec
  437. });
  438. }
  439. callback(tabs);
  440. };
  441. /******************************************************************************/
  442. vAPI.tabs.getWindows = function() {
  443. var winumerator = Services.wm.getEnumerator('navigator:browser');
  444. var windows = [];
  445. while ( winumerator.hasMoreElements() ) {
  446. var win = winumerator.getNext();
  447. if ( !win.closed ) {
  448. windows.push(win);
  449. }
  450. }
  451. return windows;
  452. };
  453. /******************************************************************************/
  454. // properties of the details object:
  455. // url: 'URL', // the address that will be opened
  456. // tabId: 1, // the tab is used if set, instead of creating a new one
  457. // index: -1, // undefined: end of the list, -1: following tab, or after index
  458. // active: false, // opens the tab in background - true and undefined: foreground
  459. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  460. vAPI.tabs.open = function(details) {
  461. if ( !details.url ) {
  462. return null;
  463. }
  464. // extension pages
  465. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  466. details.url = vAPI.getURL(details.url);
  467. }
  468. var tab;
  469. if ( details.select ) {
  470. var URI = Services.io.newURI(details.url, null, null);
  471. for ( tab of this.getAllSync() ) {
  472. var browser = tabWatcher.browserFromTarget(tab);
  473. // Or simply .equals if we care about the fragment
  474. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  475. continue;
  476. }
  477. this.select(tab);
  478. return;
  479. }
  480. }
  481. if ( details.active === undefined ) {
  482. details.active = true;
  483. }
  484. if ( details.tabId ) {
  485. tab = tabWatcher.browserFromTabId(details.tabId);
  486. if ( tab ) {
  487. tabWatcher.browserFromTarget(tab).loadURI(details.url);
  488. return;
  489. }
  490. }
  491. var win = Services.wm.getMostRecentWindow('navigator:browser');
  492. var tabBrowser = getTabBrowser(win);
  493. if ( details.index === -1 ) {
  494. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  495. }
  496. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  497. if ( details.index !== undefined ) {
  498. tabBrowser.moveTabTo(tab, details.index);
  499. }
  500. };
  501. /******************************************************************************/
  502. // Replace the URL of a tab. Noop if the tab does not exist.
  503. vAPI.tabs.replace = function(tabId, url) {
  504. var targetURL = url;
  505. // extension pages
  506. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  507. targetURL = vAPI.getURL(targetURL);
  508. }
  509. var browser = tabWatcher.browserFromTabId(tabId);
  510. if ( browser ) {
  511. browser.loadURI(targetURL);
  512. }
  513. };
  514. /******************************************************************************/
  515. vAPI.tabs._remove = function(tab, tabBrowser) {
  516. tabBrowser.removeTab(tab);
  517. };
  518. /******************************************************************************/
  519. vAPI.tabs.remove = function(tabId) {
  520. var browser = tabWatcher.browserFromTabId(tabId);
  521. if ( !browser ) {
  522. return;
  523. }
  524. var tab = tabWatcher.tabFromBrowser(browser);
  525. if ( !tab ) {
  526. return;
  527. }
  528. this._remove(tab, getTabBrowser(getOwnerWindow(browser)));
  529. };
  530. /******************************************************************************/
  531. vAPI.tabs.reload = function(tabId) {
  532. var browser = tabWatcher.browserFromTabId(tabId);
  533. if ( !browser ) {
  534. return;
  535. }
  536. browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
  537. };
  538. /******************************************************************************/
  539. vAPI.tabs.select = function(tab) {
  540. if ( typeof tab !== 'object' ) {
  541. tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
  542. }
  543. if ( !tab ) {
  544. return;
  545. }
  546. var tabBrowser = getTabBrowser(getOwnerWindow(tab)).selectedTab = tab;
  547. };
  548. /******************************************************************************/
  549. vAPI.tabs.injectScript = function(tabId, details, callback) {
  550. var browser = tabWatcher.browserFromTabId(tabId);
  551. if ( !browser ) {
  552. return;
  553. }
  554. if ( typeof details.file !== 'string' ) {
  555. return;
  556. }
  557. details.file = vAPI.getURL(details.file);
  558. browser.messageManager.sendAsyncMessage(
  559. location.host + ':broadcast',
  560. JSON.stringify({
  561. broadcast: true,
  562. channelName: 'vAPI',
  563. msg: {
  564. cmd: 'injectScript',
  565. details: details
  566. }
  567. })
  568. );
  569. if ( typeof callback === 'function' ) {
  570. vAPI.setTimeout(callback, 13);
  571. }
  572. };
  573. /******************************************************************************/
  574. // Firefox:
  575. // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
  576. //
  577. // browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
  578. // ^ |
  579. // | |
  580. // +-------------------------------------------------------------------
  581. //
  582. // browser (browser)
  583. // contentTitle
  584. // currentURI
  585. // ownerDocument (XULDocument)
  586. // defaultView (ChromeWindow)
  587. // gBrowser (tabbrowser OR browser)
  588. // browsers (browser)
  589. // selectedBrowser
  590. // selectedTab
  591. // tabs (tab.tabbrowser-tab)
  592. //
  593. // Fennec: (what I figured so far)
  594. //
  595. // tab --> browser windows --> window --> BrowserApp --> tabs --+
  596. // ^ window |
  597. // | |
  598. // +---------------------------------------------------------------+
  599. //
  600. // tab
  601. // browser
  602. // [manual search to go back to tab from list of windows]
  603. var tabWatcher = (function() {
  604. // TODO: find out whether we need a janitor to take care of stale entries.
  605. var browserToTabIdMap = new Map();
  606. var tabIdToBrowserMap = new Map();
  607. var tabIdGenerator = 1;
  608. var indexFromBrowser = function(browser) {
  609. var win = getOwnerWindow(browser);
  610. if ( !win ) {
  611. return -1;
  612. }
  613. var tabbrowser = getTabBrowser(win);
  614. if ( !tabbrowser ) {
  615. return -1;
  616. }
  617. // This can happen, for example, the `view-source:` window, there is
  618. // no tabbrowser object, the browser object sits directly in the
  619. // window.
  620. if ( tabbrowser === browser ) {
  621. return 0;
  622. }
  623. // Fennec
  624. // https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/BrowserApp
  625. if ( vAPI.fennec ) {
  626. return tabbrowser.tabs.indexOf(tabbrowser.getTabForBrowser(browser));
  627. }
  628. return tabbrowser.browsers.indexOf(browser);
  629. };
  630. var indexFromTarget = function(target) {
  631. return indexFromBrowser(browserFromTarget(target));
  632. };
  633. var tabFromBrowser = function(browser) {
  634. var i = indexFromBrowser(browser);
  635. if ( i === -1 ) {
  636. return null;
  637. }
  638. var win = getOwnerWindow(browser);
  639. if ( !win ) {
  640. return null;
  641. }
  642. var tabbrowser = getTabBrowser(win);
  643. if ( !tabbrowser ) {
  644. return null;
  645. }
  646. if ( !tabbrowser.tabs || i >= tabbrowser.tabs.length ) {
  647. return null;
  648. }
  649. return tabbrowser.tabs[i];
  650. };
  651. var browserFromTarget = function(target) {
  652. if ( !target ) {
  653. return null;
  654. }
  655. if ( vAPI.fennec ) {
  656. if ( target.browser ) { // target is a tab
  657. target = target.browser;
  658. }
  659. } else if ( target.linkedPanel ) { // target is a tab
  660. target = target.linkedBrowser;
  661. }
  662. if ( target.localName !== 'browser' ) {
  663. return null;
  664. }
  665. return target;
  666. };
  667. var tabIdFromTarget = function(target) {
  668. var browser = browserFromTarget(target);
  669. if ( browser === null ) {
  670. return vAPI.noTabId;
  671. }
  672. var tabId = browserToTabIdMap.get(browser);
  673. if ( tabId === undefined ) {
  674. tabId = '' + tabIdGenerator++;
  675. browserToTabIdMap.set(browser, tabId);
  676. tabIdToBrowserMap.set(tabId, browser);
  677. }
  678. return tabId;
  679. };
  680. var browserFromTabId = function(tabId) {
  681. var browser = tabIdToBrowserMap.get(tabId);
  682. if ( browser === undefined ) {
  683. return null;
  684. }
  685. // Verify that the browser is still live
  686. if ( indexFromBrowser(browser) !== -1 ) {
  687. return browser;
  688. }
  689. removeBrowserEntry(tabId, browser);
  690. return null;
  691. };
  692. var currentBrowser = function() {
  693. var win = Services.wm.getMostRecentWindow('navigator:browser');
  694. // https://github.com/gorhill/uBlock/issues/399
  695. // getTabBrowser() can return null at browser launch time.
  696. var tabBrowser = getTabBrowser(win);
  697. if ( tabBrowser === null ) {
  698. return null;
  699. }
  700. return browserFromTarget(tabBrowser.selectedTab);
  701. };
  702. var removeBrowserEntry = function(tabId, browser) {
  703. if ( tabId && tabId !== vAPI.noTabId ) {
  704. vAPI.tabs.onClosed(tabId);
  705. delete vAPI.toolbarButton.tabs[tabId];
  706. tabIdToBrowserMap.delete(tabId);
  707. }
  708. if ( browser ) {
  709. browserToTabIdMap.delete(browser);
  710. }
  711. };
  712. // https://developer.mozilla.org/en-US/docs/Web/Events/TabOpen
  713. var onOpen = function({target}) {
  714. var tabId = tabIdFromTarget(target);
  715. var browser = browserFromTabId(tabId);
  716. vAPI.tabs.onNavigation({
  717. frameId: 0,
  718. tabId: tabId,
  719. url: browser.currentURI.asciiSpec,
  720. });
  721. };
  722. // https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
  723. var onShow = function({target}) {
  724. tabIdFromTarget(target);
  725. };
  726. // https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
  727. var onClose = function({target}) {
  728. // target is tab in Firefox, browser in Fennec
  729. var browser = browserFromTarget(target);
  730. var tabId = browserToTabIdMap.get(browser);
  731. removeBrowserEntry(tabId, browser);
  732. };
  733. // https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
  734. var onSelect = function({target}) {
  735. vAPI.setIcon(tabIdFromTarget(target), getOwnerWindow(target));
  736. };
  737. var locationChangedMessageName = location.host + ':locationChanged';
  738. var onLocationChanged = function(e) {
  739. var vapi = vAPI;
  740. var details = e.data;
  741. // Ignore notifications related to our popup
  742. if ( details.url.lastIndexOf(vapi.getURL('popup.html'), 0) === 0 ) {
  743. return;
  744. }
  745. var browser = e.target;
  746. var tabId = tabIdFromTarget(browser);
  747. if ( tabId === vapi.noTabId ) {
  748. return;
  749. }
  750. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  751. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  752. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  753. vapi.tabs.onUpdated(tabId, {url: details.url}, {
  754. frameId: 0,
  755. tabId: tabId,
  756. url: browser.currentURI.asciiSpec
  757. });
  758. return;
  759. }
  760. // https://github.com/chrisaljoudi/uBlock/issues/105
  761. // Allow any kind of pages
  762. vapi.tabs.onNavigation({
  763. frameId: 0,
  764. tabId: tabId,
  765. url: details.url,
  766. });
  767. };
  768. var onWindowLoad = function(ev) {
  769. if ( ev ) {
  770. this.removeEventListener(ev.type, onWindowLoad);
  771. }
  772. var wintype = this.document.documentElement.getAttribute('windowtype');
  773. if ( wintype !== 'navigator:browser' ) {
  774. return;
  775. }
  776. var tabBrowser = getTabBrowser(this);
  777. if ( !tabBrowser ) {
  778. return;
  779. }
  780. var tabContainer = tabBrowser.tabContainer;
  781. if ( !tabContainer ) {
  782. return;
  783. }
  784. vAPI.contextMenu.register(this.document);
  785. tabContainer.addEventListener('TabOpen', onOpen);
  786. tabContainer.addEventListener('TabShow', onShow);
  787. tabContainer.addEventListener('TabClose', onClose);
  788. tabContainer.addEventListener('TabSelect', onSelect);
  789. // when new window is opened TabSelect doesn't run on the selected tab?
  790. };
  791. var onWindowUnload = function() {
  792. vAPI.contextMenu.unregister(this.document);
  793. this.removeEventListener('DOMContentLoaded', onWindowLoad);
  794. var tabBrowser = getTabBrowser(this);
  795. if ( !tabBrowser ) {
  796. return;
  797. }
  798. var tabContainer = null;
  799. if ( tabBrowser.tabContainer ) {
  800. tabContainer = tabBrowser.tabContainer;
  801. }
  802. if ( tabContainer ) {
  803. tabContainer.removeEventListener('TabOpen', onOpen);
  804. tabContainer.removeEventListener('TabShow', onShow);
  805. tabContainer.removeEventListener('TabClose', onClose);
  806. tabContainer.removeEventListener('TabSelect', onSelect);
  807. }
  808. var browser, URI, tabId;
  809. for ( var tab of tabBrowser.tabs ) {
  810. browser = tabWatcher.browserFromTarget(tab);
  811. if ( browser === null ) {
  812. continue;
  813. }
  814. URI = browser.currentURI;
  815. // Close extension tabs
  816. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  817. vAPI.tabs._remove(tab, getTabBrowser(this));
  818. }
  819. browser = browserFromTarget(tab);
  820. tabId = browserToTabIdMap.get(browser);
  821. if ( tabId !== undefined ) {
  822. removeBrowserEntry(tabId, browser);
  823. tabIdToBrowserMap.delete(tabId);
  824. }
  825. browserToTabIdMap.delete(browser);
  826. }
  827. };
  828. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
  829. var windowWatcher = {
  830. observe: function(win, topic) {
  831. if ( topic === 'domwindowopened' ) {
  832. win.addEventListener('DOMContentLoaded', onWindowLoad);
  833. return;
  834. }
  835. if ( topic === 'domwindowclosed' ) {
  836. onWindowUnload.call(win);
  837. return;
  838. }
  839. }
  840. };
  841. // Initialize map with existing active tabs
  842. var start = function() {
  843. var tabBrowser, tab;
  844. for ( var win of vAPI.tabs.getWindows() ) {
  845. onWindowLoad.call(win);
  846. tabBrowser = getTabBrowser(win);
  847. if ( tabBrowser === null ) {
  848. continue;
  849. }
  850. for ( tab of tabBrowser.tabs ) {
  851. if ( vAPI.fennec || !tab.hasAttribute('pending') ) {
  852. tabIdFromTarget(tab);
  853. }
  854. }
  855. }
  856. vAPI.messaging.globalMessageManager.addMessageListener(
  857. locationChangedMessageName,
  858. onLocationChanged
  859. );
  860. Services.ww.registerNotification(windowWatcher);
  861. };
  862. var stop = function() {
  863. vAPI.messaging.globalMessageManager.removeMessageListener(
  864. locationChangedMessageName,
  865. onLocationChanged
  866. );
  867. Services.ww.unregisterNotification(windowWatcher);
  868. for ( var win of vAPI.tabs.getWindows() ) {
  869. onWindowUnload.call(win);
  870. }
  871. browserToTabIdMap.clear();
  872. tabIdToBrowserMap.clear();
  873. };
  874. cleanupTasks.push(stop);
  875. return {
  876. browsers: function() { return browserToTabIdMap.keys(); },
  877. browserFromTabId: browserFromTabId,
  878. browserFromTarget: browserFromTarget,
  879. currentBrowser: currentBrowser,
  880. indexFromTarget: indexFromTarget,
  881. start: start,
  882. tabFromBrowser: tabFromBrowser,
  883. tabIdFromTarget: tabIdFromTarget
  884. };
  885. })();
  886. /******************************************************************************/
  887. vAPI.setIcon = function(tabId, iconId, badge) {
  888. // If badge is undefined, then setIcon was called from the TabSelect event
  889. var win;
  890. if ( badge === undefined ) {
  891. win = iconId;
  892. } else {
  893. win = Services.wm.getMostRecentWindow('navigator:browser');
  894. }
  895. var curTabId = tabWatcher.tabIdFromTarget(getTabBrowser(win).selectedTab);
  896. var tb = vAPI.toolbarButton;
  897. // from 'TabSelect' event
  898. if ( tabId === undefined ) {
  899. tabId = curTabId;
  900. } else if ( badge !== undefined ) {
  901. tb.tabs[tabId] = { badge: badge, img: iconId };
  902. }
  903. if ( tabId === curTabId ) {
  904. tb.updateState(win, tabId);
  905. }
  906. };
  907. /******************************************************************************/
  908. vAPI.messaging = {
  909. get globalMessageManager() {
  910. return Cc['@mozilla.org/globalmessagemanager;1']
  911. .getService(Ci.nsIMessageListenerManager);
  912. },
  913. frameScript: vAPI.getURL('frameScript.js'),
  914. listeners: {},
  915. defaultHandler: null,
  916. NOOPFUNC: function(){},
  917. UNHANDLED: 'vAPI.messaging.notHandled'
  918. };
  919. /******************************************************************************/
  920. vAPI.messaging.listen = function(listenerName, callback) {
  921. this.listeners[listenerName] = callback;
  922. };
  923. /******************************************************************************/
  924. vAPI.messaging.onMessage = function({target, data}) {
  925. var messageManager = target.messageManager;
  926. if ( !messageManager ) {
  927. // Message came from a popup, and its message manager is not usable.
  928. // So instead we broadcast to the parent window.
  929. messageManager = getOwnerWindow(
  930. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  931. ).messageManager;
  932. }
  933. var channelNameRaw = data.channelName;
  934. var pos = channelNameRaw.indexOf('|');
  935. var channelName = channelNameRaw.slice(pos + 1);
  936. var callback = vAPI.messaging.NOOPFUNC;
  937. if ( data.requestId !== undefined ) {
  938. callback = CallbackWrapper.factory(
  939. messageManager,
  940. channelName,
  941. channelNameRaw.slice(0, pos),
  942. data.requestId
  943. ).callback;
  944. }
  945. var sender = {
  946. tab: {
  947. id: tabWatcher.tabIdFromTarget(target)
  948. }
  949. };
  950. // Specific handler
  951. var r = vAPI.messaging.UNHANDLED;
  952. var listener = vAPI.messaging.listeners[channelName];
  953. if ( typeof listener === 'function' ) {
  954. r = listener(data.msg, sender, callback);
  955. }
  956. if ( r !== vAPI.messaging.UNHANDLED ) {
  957. return;
  958. }
  959. // Default handler
  960. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  961. if ( r !== vAPI.messaging.UNHANDLED ) {
  962. return;
  963. }
  964. console.error('uMatrix> messaging > unknown request: %o', data);
  965. // Unhandled:
  966. // Need to callback anyways in case caller expected an answer, or
  967. // else there is a memory leak on caller's side
  968. callback();
  969. };
  970. /******************************************************************************/
  971. vAPI.messaging.setup = function(defaultHandler) {
  972. // Already setup?
  973. if ( this.defaultHandler !== null ) {
  974. return;
  975. }
  976. if ( typeof defaultHandler !== 'function' ) {
  977. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  978. }
  979. this.defaultHandler = defaultHandler;
  980. this.globalMessageManager.addMessageListener(
  981. location.host + ':background',
  982. this.onMessage
  983. );
  984. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  985. cleanupTasks.push(function() {
  986. var gmm = vAPI.messaging.globalMessageManager;
  987. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  988. gmm.removeMessageListener(
  989. location.host + ':background',
  990. vAPI.messaging.onMessage
  991. );
  992. });
  993. };
  994. /******************************************************************************/
  995. vAPI.messaging.broadcast = function(message) {
  996. this.globalMessageManager.broadcastAsyncMessage(
  997. location.host + ':broadcast',
  998. JSON.stringify({broadcast: true, msg: message})
  999. );
  1000. };
  1001. /******************************************************************************/
  1002. // This allows to avoid creating a closure for every single message which
  1003. // expects an answer. Having a closure created each time a message is processed
  1004. // has been always bothering me. Another benefit of the implementation here
  1005. // is to reuse the callback proxy object, so less memory churning.
  1006. //
  1007. // https://developers.google.com/speed/articles/optimizing-javascript
  1008. // "Creating a closure is significantly slower then creating an inner
  1009. // function without a closure, and much slower than reusing a static
  1010. // function"
  1011. //
  1012. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  1013. // "the dreaded 'uniformly slow code' case where every function takes 1%
  1014. // of CPU and you have to make one hundred separate performance optimizations
  1015. // to improve performance at all"
  1016. //
  1017. // http://jsperf.com/closure-no-closure/2
  1018. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  1019. this.callback = this.proxy.bind(this); // bind once
  1020. this.init(messageManager, channelName, listenerId, requestId);
  1021. };
  1022. CallbackWrapper.junkyard = [];
  1023. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  1024. var wrapper = CallbackWrapper.junkyard.pop();
  1025. if ( wrapper ) {
  1026. wrapper.init(messageManager, channelName, listenerId, requestId);
  1027. return wrapper;
  1028. }
  1029. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  1030. };
  1031. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  1032. this.messageManager = messageManager;
  1033. this.channelName = channelName;
  1034. this.listenerId = listenerId;
  1035. this.requestId = requestId;
  1036. };
  1037. CallbackWrapper.prototype.proxy = function(response) {
  1038. var message = JSON.stringify({
  1039. requestId: this.requestId,
  1040. channelName: this.channelName,
  1041. msg: response !== undefined ? response : null
  1042. });
  1043. if ( this.messageManager.sendAsyncMessage ) {
  1044. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1045. } else {
  1046. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1047. }
  1048. // Mark for reuse
  1049. this.messageManager =
  1050. this.channelName =
  1051. this.requestId =
  1052. this.listenerId = null;
  1053. CallbackWrapper.junkyard.push(this);
  1054. };
  1055. /******************************************************************************/
  1056. var httpRequestHeadersFactory = function(channel) {
  1057. var entry = httpRequestHeadersFactory.junkyard.pop();
  1058. if ( entry ) {
  1059. return entry.init(channel);
  1060. }
  1061. return new HTTPRequestHeaders(channel);
  1062. };
  1063. httpRequestHeadersFactory.junkyard = [];
  1064. var HTTPRequestHeaders = function(channel) {
  1065. this.init(channel);
  1066. };
  1067. HTTPRequestHeaders.prototype.init = function(channel) {
  1068. this.channel = channel;
  1069. return this;
  1070. };
  1071. HTTPRequestHeaders.prototype.dispose = function() {
  1072. this.channel = null;
  1073. httpRequestHeadersFactory.junkyard.push(this);
  1074. };
  1075. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1076. try {
  1077. return this.channel.getRequestHeader(name);
  1078. } catch (e) {
  1079. }
  1080. return '';
  1081. };
  1082. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1083. var oldValue = this.getHeader(name);
  1084. if ( newValue === oldValue ) {
  1085. return false;
  1086. }
  1087. if ( oldValue === '' && create !== true ) {
  1088. return false;
  1089. }
  1090. this.channel.setRequestHeader(name, newValue, false);
  1091. return true;
  1092. };
  1093. /******************************************************************************/
  1094. var httpObserver = {
  1095. classDescription: 'net-channel-event-sinks for ' + location.host,
  1096. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1097. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1098. REQDATAKEY: location.host + 'reqdata',
  1099. ABORT: Components.results.NS_BINDING_ABORTED,
  1100. ACCEPT: Components.results.NS_SUCCEEDED,
  1101. // Request types:
  1102. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1103. frameTypeMap: {
  1104. 6: 'main_frame',
  1105. 7: 'sub_frame'
  1106. },
  1107. typeMap: {
  1108. 1: 'other',
  1109. 2: 'script',
  1110. 3: 'image',
  1111. 4: 'stylesheet',
  1112. 5: 'object',
  1113. 6: 'main_frame',
  1114. 7: 'sub_frame',
  1115. 10: 'ping',
  1116. 11: 'xmlhttprequest',
  1117. 12: 'object',
  1118. 14: 'font',
  1119. 15: 'media',
  1120. 16: 'websocket',
  1121. 21: 'image'
  1122. },
  1123. mimeTypeMap: {
  1124. 'audio': 15,
  1125. 'video': 15
  1126. },
  1127. get componentRegistrar() {
  1128. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1129. },
  1130. get categoryManager() {
  1131. return Cc['@mozilla.org/categorymanager;1']
  1132. .getService(Ci.nsICategoryManager);
  1133. },
  1134. QueryInterface: (function() {
  1135. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1136. return XPCOMUtils.generateQI([
  1137. Ci.nsIFactory,
  1138. Ci.nsIObserver,
  1139. Ci.nsIChannelEventSink,
  1140. Ci.nsISupportsWeakReference
  1141. ]);
  1142. })(),
  1143. createInstance: function(outer, iid) {
  1144. if ( outer ) {
  1145. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1146. }
  1147. return this.QueryInterface(iid);
  1148. },
  1149. register: function() {
  1150. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1151. Services.obs.addObserver(this, 'http-on-opening-request', true);
  1152. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1153. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1154. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1155. // Guard against stale instances not having been unregistered
  1156. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1157. try {
  1158. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1159. } catch (ex) {
  1160. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1161. }
  1162. }
  1163. this.componentRegistrar.registerFactory(
  1164. this.classID,
  1165. this.classDescription,
  1166. this.contractID,
  1167. this
  1168. );
  1169. this.categoryManager.addCategoryEntry(
  1170. 'net-channel-event-sinks',
  1171. this.contractID,
  1172. this.contractID,
  1173. false,
  1174. true
  1175. );
  1176. },
  1177. unregister: function() {
  1178. Services.obs.removeObserver(this, 'http-on-opening-request');
  1179. Services.obs.removeObserver(this, 'http-on-modify-request');
  1180. Services.obs.removeObserver(this, 'http-on-examine-response');
  1181. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1182. this.componentRegistrar.unregisterFactory(this.classID, this);
  1183. this.categoryManager.deleteCategoryEntry(
  1184. 'net-channel-event-sinks',
  1185. this.contractID,
  1186. false
  1187. );
  1188. },
  1189. handleRequest: function(channel, URI, tabId, rawtype) {
  1190. var type = this.typeMap[rawtype] || 'other';
  1191. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1192. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  1193. return false;
  1194. }
  1195. var result = onBeforeRequest.callback({
  1196. hostname: URI.asciiHost,
  1197. parentFrameId: type === 'main_frame' ? -1 : 0,
  1198. tabId: tabId,
  1199. type: type,
  1200. url: URI.asciiSpec
  1201. });
  1202. if ( typeof result !== 'object' ) {
  1203. return false;
  1204. }
  1205. channel.cancel(this.ABORT);
  1206. return true;
  1207. },
  1208. handleRequestHeaders: function(channel, URI, tabId, rawtype) {
  1209. var type = this.typeMap[rawtype] || 'other';
  1210. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1211. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  1212. return;
  1213. }
  1214. var requestHeaders = httpRequestHeadersFactory(channel);
  1215. onBeforeSendHeaders.callback({
  1216. hostname: URI.asciiHost,
  1217. parentFrameId: type === 'main_frame' ? -1 : 0,
  1218. requestHeaders: requestHeaders,
  1219. tabId: tabId,
  1220. type: type,
  1221. url: URI.asciiSpec
  1222. });
  1223. requestHeaders.dispose();
  1224. },
  1225. channelDataFromChannel: function(channel) {
  1226. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1227. try {
  1228. return channel.getProperty(this.REQDATAKEY);
  1229. } catch (ex) {
  1230. }
  1231. }
  1232. return null;
  1233. },
  1234. // https://github.com/gorhill/uMatrix/issues/165
  1235. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1236. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1237. // care about embedded frames topography.
  1238. // Also:
  1239. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1240. tabIdFromChannel: function(channel) {
  1241. var aWindow;
  1242. if ( channel.notificationCallbacks ) {
  1243. try {
  1244. var loadContext = channel
  1245. .notificationCallbacks
  1246. .getInterface(Ci.nsILoadContext);
  1247. if ( loadContext.topFrameElement ) {
  1248. return tabWatcher.tabIdFromTarget(loadContext.topFrameElement);
  1249. }
  1250. aWindow = loadContext.associatedWindow;
  1251. } catch (ex) {
  1252. //console.error(ex);
  1253. }
  1254. }
  1255. try {
  1256. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  1257. aWindow = channel
  1258. .loadGroup
  1259. .notificationCallbacks
  1260. .getInterface(Ci.nsILoadContext)
  1261. .associatedWindow;
  1262. }
  1263. if ( aWindow ) {
  1264. return tabWatcher.tabIdFromTarget(
  1265. aWindow
  1266. .getInterface(Ci.nsIWebNavigation)
  1267. .QueryInterface(Ci.nsIDocShell)
  1268. .rootTreeItem
  1269. .QueryInterface(Ci.nsIInterfaceRequestor)
  1270. .getInterface(Ci.nsIDOMWindow)
  1271. .gBrowser
  1272. .getBrowserForContentWindow(aWindow)
  1273. );
  1274. }
  1275. } catch (ex) {
  1276. //console.error(ex);
  1277. }
  1278. return vAPI.noTabId;
  1279. },
  1280. rawtypeFromContentType: function(channel) {
  1281. var mime = channel.contentType;
  1282. if ( !mime ) {
  1283. return 0;
  1284. }
  1285. var pos = mime.indexOf('/');
  1286. if ( pos === -1 ) {
  1287. pos = mime.length;
  1288. }
  1289. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1290. },
  1291. observe: function(channel, topic) {
  1292. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1293. return;
  1294. }
  1295. var URI = channel.URI;
  1296. var channelData, tabId, rawtype;
  1297. if (
  1298. topic === 'http-on-examine-response' ||
  1299. topic === 'http-on-examine-cached-response'
  1300. ) {
  1301. channelData = this.channelDataFromChannel(channel);
  1302. if ( channelData === null ) {
  1303. return;
  1304. }
  1305. var type = this.frameTypeMap[channelData[1]];
  1306. if ( !type ) {
  1307. return;
  1308. }
  1309. topic = 'Content-Security-Policy';
  1310. var result;
  1311. try {
  1312. result = channel.getResponseHeader(topic);
  1313. } catch (ex) {
  1314. result = null;
  1315. }
  1316. result = vAPI.net.onHeadersReceived.callback({
  1317. hostname: URI.asciiHost,
  1318. parentFrameId: type === 'main_frame' ? -1 : 0,
  1319. responseHeaders: result ? [{name: topic, value: result}] : [],
  1320. tabId: channelData[0],
  1321. type: type,
  1322. url: URI.asciiSpec
  1323. });
  1324. if ( result ) {
  1325. channel.setResponseHeader(
  1326. topic,
  1327. result.responseHeaders.pop().value,
  1328. true
  1329. );
  1330. }
  1331. return;
  1332. }
  1333. if ( topic === 'http-on-modify-request' ) {
  1334. channelData = this.channelDataFromChannel(channel);
  1335. if ( channelData === null ) {
  1336. return;
  1337. }
  1338. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1339. return;
  1340. }
  1341. // http-on-opening-request
  1342. tabId = this.tabIdFromChannel(channel);
  1343. rawtype = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1344. if ( this.handleRequest(channel, URI, tabId, rawtype) === true ) {
  1345. return;
  1346. }
  1347. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1348. return;
  1349. }
  1350. // Carry data for behind-the-scene redirects
  1351. channel.setProperty(this.REQDATAKEY, [tabId, rawtype]);
  1352. },
  1353. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1354. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1355. var result = this.ACCEPT;
  1356. // If error thrown, the redirect will fail
  1357. try {
  1358. var URI = newChannel.URI;
  1359. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1360. return;
  1361. }
  1362. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1363. return;
  1364. }
  1365. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1366. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1367. result = this.ABORT;
  1368. return;
  1369. }
  1370. // Carry the data on in case of multiple redirects
  1371. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1372. newChannel.setProperty(this.REQDATAKEY, channelData);
  1373. }
  1374. } catch (ex) {
  1375. // console.error(ex);
  1376. } finally {
  1377. callback.onRedirectVerifyCallback(result);
  1378. }
  1379. }
  1380. };
  1381. /******************************************************************************/
  1382. vAPI.net = {};
  1383. /******************************************************************************/
  1384. vAPI.net.registerListeners = function() {
  1385. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1386. new Set(this.onBeforeRequest.types) :
  1387. null;
  1388. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1389. new Set(this.onBeforeSendHeaders.types) :
  1390. null;
  1391. httpObserver.register();
  1392. cleanupTasks.push(function() {
  1393. httpObserver.unregister();
  1394. });
  1395. };
  1396. /******************************************************************************/
  1397. vAPI.toolbarButton = {
  1398. id: location.host + '-button',
  1399. type: 'view',
  1400. viewId: location.host + '-panel',
  1401. label: vAPI.app.name,
  1402. tooltiptext: vAPI.app.name,
  1403. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1404. };
  1405. /******************************************************************************/
  1406. // Toolbar button UI for desktop Firefox
  1407. vAPI.toolbarButton.init = function() {
  1408. var CustomizableUI;
  1409. try {
  1410. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1411. } catch (ex) {
  1412. return;
  1413. }
  1414. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1415. this.styleURI = [
  1416. '#' + this.id + ' {',
  1417. 'list-style-image: url(',
  1418. vAPI.getURL('img/browsericons/icon19-off.png'),
  1419. ');',
  1420. '}',
  1421. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1422. 'width: 160px;',
  1423. 'height: 290px;',
  1424. 'overflow: hidden !important;',
  1425. '}'
  1426. ];
  1427. var platformVersion = Services.appinfo.platformVersion;
  1428. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1429. this.styleURI.push(
  1430. '#' + this.id + '[badge]:not([badge=""])::after {',
  1431. 'position: absolute;',
  1432. 'margin-left: -16px;',
  1433. 'margin-top: 3px;',
  1434. 'padding: 1px 2px;',
  1435. 'font-size: 9px;',
  1436. 'font-weight: bold;',
  1437. 'color: #fff;',
  1438. 'background: #000;',
  1439. 'content: attr(badge);',
  1440. '}'
  1441. );
  1442. } else {
  1443. this.CUIEvents = {};
  1444. var updateBadge = function() {
  1445. var wId = vAPI.toolbarButton.id;
  1446. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1447. for ( var win of vAPI.tabs.getWindows() ) {
  1448. var button = win.document.getElementById(wId);
  1449. if ( buttonInPanel ) {
  1450. button.classList.remove('badged-button');
  1451. continue;
  1452. }
  1453. if ( button === null ) {
  1454. continue;
  1455. }
  1456. button.classList.add('badged-button');
  1457. }
  1458. if ( buttonInPanel ) {
  1459. return;
  1460. }
  1461. // Anonymous elements need some time to be reachable
  1462. vAPI.setTimeout(this.updateBadgeStyle, 250);
  1463. }.bind(this.CUIEvents);
  1464. this.CUIEvents.onCustomizeEnd = updateBadge;
  1465. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1466. this.CUIEvents.updateBadgeStyle = function() {
  1467. var css = [
  1468. 'background: #000',
  1469. 'color: #fff'
  1470. ].join(';');
  1471. for ( var win of vAPI.tabs.getWindows() ) {
  1472. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1473. if ( button === null ) {
  1474. continue;
  1475. }
  1476. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1477. button,
  1478. 'class',
  1479. 'toolbarbutton-badge'
  1480. );
  1481. if ( !badge ) {
  1482. return;
  1483. }
  1484. badge.style.cssText = css;
  1485. }
  1486. };
  1487. this.onCreated = function(button) {
  1488. button.setAttribute('badge', '');
  1489. vAPI.setTimeout(updateBadge, 250);
  1490. };
  1491. CustomizableUI.addListener(this.CUIEvents);
  1492. }
  1493. this.styleURI = Services.io.newURI(
  1494. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1495. null,
  1496. null
  1497. );
  1498. this.closePopup = function({target}) {
  1499. CustomizableUI.hidePanelForNode(
  1500. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1501. );
  1502. };
  1503. CustomizableUI.createWidget(this);
  1504. vAPI.messaging.globalMessageManager.addMessageListener(
  1505. location.host + ':closePopup',
  1506. this.closePopup
  1507. );
  1508. cleanupTasks.push(function() {
  1509. if ( this.CUIEvents ) {
  1510. CustomizableUI.removeListener(this.CUIEvents);
  1511. }
  1512. CustomizableUI.destroyWidget(this.id);
  1513. vAPI.messaging.globalMessageManager.removeMessageListener(
  1514. location.host + ':closePopup',
  1515. this.closePopup
  1516. );
  1517. for ( var win of vAPI.tabs.getWindows() ) {
  1518. var panel = win.document.getElementById(this.viewId);
  1519. panel.parentNode.removeChild(panel);
  1520. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1521. .getInterface(Ci.nsIDOMWindowUtils)
  1522. .removeSheet(this.styleURI, 1);
  1523. }
  1524. }.bind(this));
  1525. this.init = null;
  1526. };
  1527. /******************************************************************************/
  1528. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1529. var panel = doc.createElement('panelview');
  1530. panel.setAttribute('id', this.viewId);
  1531. var iframe = doc.createElement('iframe');
  1532. iframe.setAttribute('type', 'content');
  1533. iframe.setAttribute('overflow-x', 'hidden');
  1534. doc.getElementById('PanelUI-multiView')
  1535. .appendChild(panel)
  1536. .appendChild(iframe);
  1537. var scrollBarWidth = 0;
  1538. var updateTimer = null;
  1539. var delayedResize = function() {
  1540. if ( updateTimer ) {
  1541. return;
  1542. }
  1543. updateTimer = vAPI.setTimeout(resizePopup, 10);
  1544. };
  1545. var resizePopup = function() {
  1546. updateTimer = null;
  1547. var body = iframe.contentDocument.body;
  1548. panel.parentNode.style.maxWidth = 'none';
  1549. // We set a limit for height
  1550. var height = Math.min(body.clientHeight, 600);
  1551. // https://github.com/chrisaljoudi/uBlock/issues/730
  1552. // Voodoo programming: this recipe works
  1553. panel.style.setProperty('height', height + 'px');
  1554. iframe.style.setProperty('height', height + 'px');
  1555. // Adjust width for presence/absence of vertical scroll bar which may
  1556. // have appeared as a result of last operation.
  1557. var contentWindow = iframe.contentWindow;
  1558. var width = body.clientWidth;
  1559. if ( contentWindow.scrollMaxY !== 0 ) {
  1560. width += scrollBarWidth;
  1561. }
  1562. panel.style.setProperty('width', width + 'px');
  1563. // scrollMaxX should always be zero once we know the scrollbar width
  1564. if ( contentWindow.scrollMaxX !== 0 ) {
  1565. scrollBarWidth = contentWindow.scrollMaxX;
  1566. width += scrollBarWidth;
  1567. panel.style.setProperty('width', width + 'px');
  1568. }
  1569. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1570. delayedResize();
  1571. return;
  1572. }
  1573. };
  1574. var onPopupReady = function() {
  1575. var win = this.contentWindow;
  1576. if ( !win || win.location.host !== location.host ) {
  1577. return;
  1578. }
  1579. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1580. attributes: true,
  1581. characterData: true,
  1582. subtree: true
  1583. });
  1584. delayedResize();
  1585. };
  1586. iframe.addEventListener('load', onPopupReady, true);
  1587. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1588. .getInterface(Ci.nsIDOMWindowUtils)
  1589. .loadSheet(this.styleURI, 1);
  1590. };
  1591. /******************************************************************************/
  1592. vAPI.toolbarButton.onViewShowing = function({target}) {
  1593. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1594. };
  1595. /******************************************************************************/
  1596. vAPI.toolbarButton.onViewHiding = function({target}) {
  1597. target.parentNode.style.maxWidth = '';
  1598. target.firstChild.setAttribute('src', 'about:blank');
  1599. };
  1600. /******************************************************************************/
  1601. vAPI.toolbarButton.updateState = function(win, tabId) {
  1602. var button = win.document.getElementById(this.id);
  1603. if ( !button ) {
  1604. return;
  1605. }
  1606. var icon = this.tabs[tabId];
  1607. button.setAttribute('badge', icon && icon.badge || '');
  1608. var iconId = icon && icon.img ? icon.img : 'off';
  1609. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1610. button.style.listStyleImage = icon;
  1611. };
  1612. /******************************************************************************/
  1613. vAPI.toolbarButton.init();
  1614. /******************************************************************************/
  1615. /******************************************************************************/
  1616. vAPI.contextMenu = {
  1617. contextMap: {
  1618. frame: 'inFrame',
  1619. link: 'onLink',
  1620. image: 'onImage',
  1621. audio: 'onAudio',
  1622. video: 'onVideo',
  1623. editable: 'onEditableArea'
  1624. }
  1625. };
  1626. /******************************************************************************/
  1627. vAPI.contextMenu.displayMenuItem = function({target}) {
  1628. var doc = target.ownerDocument;
  1629. var gContextMenu = doc.defaultView.gContextMenu;
  1630. if ( !gContextMenu.browser ) {
  1631. return;
  1632. }
  1633. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1634. var currentURI = gContextMenu.browser.currentURI;
  1635. // https://github.com/chrisaljoudi/uBlock/issues/105
  1636. // TODO: Should the element picker works on any kind of pages?
  1637. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1638. menuitem.hidden = true;
  1639. return;
  1640. }
  1641. var ctx = vAPI.contextMenu.contexts;
  1642. if ( !ctx ) {
  1643. menuitem.hidden = false;
  1644. return;
  1645. }
  1646. var ctxMap = vAPI.contextMenu.contextMap;
  1647. for ( var context of ctx ) {
  1648. if (
  1649. context === 'page' &&
  1650. !gContextMenu.onLink &&
  1651. !gContextMenu.onImage &&
  1652. !gContextMenu.onEditableArea &&
  1653. !gContextMenu.inFrame &&
  1654. !gContextMenu.onVideo &&
  1655. !gContextMenu.onAudio
  1656. ) {
  1657. menuitem.hidden = false;
  1658. return;
  1659. }
  1660. if ( gContextMenu[ctxMap[context]] ) {
  1661. menuitem.hidden = false;
  1662. return;
  1663. }
  1664. }
  1665. menuitem.hidden = true;
  1666. };
  1667. /******************************************************************************/
  1668. vAPI.contextMenu.register = function(doc) {
  1669. if ( !this.menuItemId ) {
  1670. return;
  1671. }
  1672. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1673. var menuitem = doc.createElement('menuitem');
  1674. menuitem.setAttribute('id', this.menuItemId);
  1675. menuitem.setAttribute('label', this.menuLabel);
  1676. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1677. menuitem.setAttribute('class', 'menuitem-iconic');
  1678. menuitem.addEventListener('command', this.onCommand);
  1679. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1680. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1681. };
  1682. /******************************************************************************/
  1683. vAPI.contextMenu.unregister = function(doc) {
  1684. if ( !this.menuItemId ) {
  1685. return;
  1686. }
  1687. var menuitem = doc.getElementById(this.menuItemId);
  1688. var contextMenu = menuitem.parentNode;
  1689. menuitem.removeEventListener('command', this.onCommand);
  1690. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1691. contextMenu.removeChild(menuitem);
  1692. };
  1693. /******************************************************************************/
  1694. vAPI.contextMenu.create = function(details, callback) {
  1695. this.menuItemId = details.id;
  1696. this.menuLabel = details.title;
  1697. this.contexts = details.contexts;
  1698. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1699. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1700. } else {
  1701. // default in Chrome
  1702. this.contexts = ['page'];
  1703. }
  1704. this.onCommand = function() {
  1705. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1706. var details = {
  1707. menuItemId: this.id
  1708. };
  1709. if ( gContextMenu.inFrame ) {
  1710. details.tagName = 'iframe';
  1711. // Probably won't work with e10s
  1712. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1713. } else if ( gContextMenu.onImage ) {
  1714. details.tagName = 'img';
  1715. details.srcUrl = gContextMenu.mediaURL;
  1716. } else if ( gContextMenu.onAudio ) {
  1717. details.tagName = 'audio';
  1718. details.srcUrl = gContextMenu.mediaURL;
  1719. } else if ( gContextMenu.onVideo ) {
  1720. details.tagName = 'video';
  1721. details.srcUrl = gContextMenu.mediaURL;
  1722. } else if ( gContextMenu.onLink ) {
  1723. details.tagName = 'a';
  1724. details.linkUrl = gContextMenu.linkURL;
  1725. }
  1726. callback(details, {
  1727. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  1728. url: gContextMenu.browser.currentURI.asciiSpec
  1729. });
  1730. };
  1731. for ( var win of vAPI.tabs.getWindows() ) {
  1732. this.register(win.document);
  1733. }
  1734. };
  1735. /******************************************************************************/
  1736. vAPI.contextMenu.remove = function() {
  1737. for ( var win of vAPI.tabs.getWindows() ) {
  1738. this.unregister(win.document);
  1739. }
  1740. this.menuItemId = null;
  1741. this.menuLabel = null;
  1742. this.contexts = null;
  1743. this.onCommand = null;
  1744. };
  1745. /******************************************************************************/
  1746. /******************************************************************************/
  1747. var optionsObserver = {
  1748. addonId: 'uMatrix@raymondhill.net',
  1749. register: function() {
  1750. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1751. cleanupTasks.push(this.unregister.bind(this));
  1752. var browser = tabWatcher.currentBrowser();
  1753. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1754. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1755. }
  1756. },
  1757. unregister: function() {
  1758. Services.obs.removeObserver(this, 'addon-options-displayed');
  1759. },
  1760. setupOptionsButton: function(doc, id, page) {
  1761. var button = doc.getElementById(id);
  1762. if ( button === null ) {
  1763. return;
  1764. }
  1765. button.addEventListener('command', function() {
  1766. vAPI.tabs.open({ url: page, index: -1 });
  1767. });
  1768. button.label = vAPI.i18n(id);
  1769. },
  1770. observe: function(doc, topic, addonId) {
  1771. if ( addonId !== this.addonId ) {
  1772. return;
  1773. }
  1774. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1775. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  1776. }
  1777. };
  1778. optionsObserver.register();
  1779. /******************************************************************************/
  1780. /******************************************************************************/
  1781. vAPI.lastError = function() {
  1782. return null;
  1783. };
  1784. /******************************************************************************/
  1785. /******************************************************************************/
  1786. // This is called only once, when everything has been loaded in memory after
  1787. // the extension was launched. It can be used to inject content scripts
  1788. // in already opened web pages, to remove whatever nuisance could make it to
  1789. // the web pages before uBlock was ready.
  1790. vAPI.onLoadAllCompleted = function() {
  1791. for ( var browser of tabWatcher.browsers() ) {
  1792. browser.messageManager.sendAsyncMessage(
  1793. location.host + '-load-completed'
  1794. );
  1795. }
  1796. };
  1797. /******************************************************************************/
  1798. /******************************************************************************/
  1799. // Likelihood is that we do not have to punycode: given punycode overhead,
  1800. // it's faster to check and skip than do it unconditionally all the time.
  1801. var punycodeHostname = punycode.toASCII;
  1802. var isNotASCII = /[^\x21-\x7F]/;
  1803. vAPI.punycodeHostname = function(hostname) {
  1804. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1805. };
  1806. vAPI.punycodeURL = function(url) {
  1807. if ( isNotASCII.test(url) ) {
  1808. return Services.io.newURI(url, null, null).asciiSpec;
  1809. }
  1810. return url;
  1811. };
  1812. /******************************************************************************/
  1813. /******************************************************************************/
  1814. vAPI.browserData = {};
  1815. /******************************************************************************/
  1816. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  1817. vAPI.browserData.clearCache = function(callback) {
  1818. // PURGE_DISK_DATA_ONLY:1
  1819. // PURGE_DISK_ALL:2
  1820. // PURGE_EVERYTHING:3
  1821. // However I verified that not argument does clear the cache data.
  1822. Services.cache2.clear();
  1823. if ( typeof callback === 'function' ) {
  1824. callback();
  1825. }
  1826. };
  1827. /******************************************************************************/
  1828. vAPI.browserData.clearOrigin = function(/* domain */) {
  1829. // TODO
  1830. };
  1831. /******************************************************************************/
  1832. /******************************************************************************/
  1833. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  1834. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  1835. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  1836. vAPI.cookies = {};
  1837. /******************************************************************************/
  1838. vAPI.cookies.CookieEntry = function(ffCookie) {
  1839. this.domain = ffCookie.host;
  1840. this.name = ffCookie.name;
  1841. this.path = ffCookie.path;
  1842. this.secure = ffCookie.isSecure === true;
  1843. this.session = ffCookie.expires === 0;
  1844. this.value = ffCookie.value;
  1845. };
  1846. /******************************************************************************/
  1847. vAPI.cookies.start = function() {
  1848. Services.obs.addObserver(this, 'cookie-changed', false);
  1849. Services.obs.addObserver(this, 'private-cookie-changed', false);
  1850. cleanupTasks.push(this.stop.bind(this));
  1851. };
  1852. /******************************************************************************/
  1853. vAPI.cookies.stop = function() {
  1854. Services.obs.removeObserver(this, 'cookie-changed');
  1855. Services.obs.removeObserver(this, 'private-cookie-changed');
  1856. };
  1857. /******************************************************************************/
  1858. vAPI.cookies.observe = function(subject, topic, reason) {
  1859. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  1860. // return;
  1861. //}
  1862. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  1863. return;
  1864. }
  1865. if ( typeof this.onChanged === 'function' ) {
  1866. this.onChanged(new this.CookieEntry(subject));
  1867. }
  1868. };
  1869. /******************************************************************************/
  1870. // Meant and expected to be asynchronous.
  1871. vAPI.cookies.getAll = function(callback) {
  1872. if ( typeof callback !== 'function' ) {
  1873. return;
  1874. }
  1875. var onAsync = function() {
  1876. var out = [];
  1877. var enumerator = Services.cookies.enumerator;
  1878. var ffcookie;
  1879. while ( enumerator.hasMoreElements() ) {
  1880. ffcookie = enumerator.getNext();
  1881. if ( ffcookie instanceof Ci.nsICookie ) {
  1882. out.push(new this.CookieEntry(ffcookie));
  1883. }
  1884. }
  1885. callback(out);
  1886. };
  1887. vAPI.setTimeout(onAsync.bind(this), 0);
  1888. };
  1889. /******************************************************************************/
  1890. vAPI.cookies.remove = function(details, callback) {
  1891. var uri = Services.io.newURI(details.url, null, null);
  1892. var cookies = Services.cookies;
  1893. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  1894. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  1895. if ( typeof callback === 'function' ) {
  1896. callback({
  1897. domain: uri.asciiHost,
  1898. name: details.name,
  1899. path: uri.path
  1900. });
  1901. }
  1902. };
  1903. /******************************************************************************/
  1904. /******************************************************************************/
  1905. })();
  1906. /******************************************************************************/