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.

2253 lines
68 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 onWindowLoad = function(ev) {
  738. if ( ev ) {
  739. this.removeEventListener(ev.type, onWindowLoad);
  740. }
  741. var wintype = this.document.documentElement.getAttribute('windowtype');
  742. if ( wintype !== 'navigator:browser' ) {
  743. return;
  744. }
  745. var tabBrowser = getTabBrowser(this);
  746. if ( !tabBrowser ) {
  747. return;
  748. }
  749. var tabContainer;
  750. if ( tabBrowser.tabContainer ) {
  751. tabContainer = tabBrowser.tabContainer;
  752. vAPI.contextMenu.register(this.document);
  753. } else {
  754. return;
  755. }
  756. tabContainer.addEventListener('TabOpen', onOpen);
  757. tabContainer.addEventListener('TabShow', onShow);
  758. tabContainer.addEventListener('TabClose', onClose);
  759. tabContainer.addEventListener('TabSelect', onSelect);
  760. // when new window is opened TabSelect doesn't run on the selected tab?
  761. };
  762. var onWindowUnload = function() {
  763. vAPI.contextMenu.unregister(this.document);
  764. this.removeEventListener('DOMContentLoaded', onWindowLoad);
  765. var tabBrowser = getTabBrowser(this);
  766. if ( !tabBrowser ) {
  767. return;
  768. }
  769. var tabContainer = null;
  770. if ( tabBrowser.tabContainer ) {
  771. tabContainer = tabBrowser.tabContainer;
  772. }
  773. if ( tabContainer ) {
  774. tabContainer.removeEventListener('TabOpen', onOpen);
  775. tabContainer.removeEventListener('TabShow', onShow);
  776. tabContainer.removeEventListener('TabClose', onClose);
  777. tabContainer.removeEventListener('TabSelect', onSelect);
  778. }
  779. var browser, URI, tabId;
  780. for ( var tab of tabBrowser.tabs ) {
  781. browser = tabWatcher.browserFromTarget(tab);
  782. if ( browser === null ) {
  783. continue;
  784. }
  785. URI = browser.currentURI;
  786. // Close extension tabs
  787. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  788. vAPI.tabs._remove(tab, getTabBrowser(this));
  789. }
  790. browser = browserFromTarget(tab);
  791. tabId = browserToTabIdMap.get(browser);
  792. if ( tabId !== undefined ) {
  793. removeBrowserEntry(tabId, browser);
  794. tabIdToBrowserMap.delete(tabId);
  795. }
  796. browserToTabIdMap.delete(browser);
  797. }
  798. };
  799. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
  800. var windowWatcher = {
  801. observe: function(win, topic) {
  802. if ( topic === 'domwindowopened' ) {
  803. win.addEventListener('DOMContentLoaded', onWindowLoad);
  804. return;
  805. }
  806. if ( topic === 'domwindowclosed' ) {
  807. onWindowUnload.call(win);
  808. return;
  809. }
  810. }
  811. };
  812. // Initialize map with existing active tabs
  813. var start = function() {
  814. var tabBrowser, tab;
  815. for ( var win of vAPI.tabs.getWindows() ) {
  816. onWindowLoad.call(win);
  817. tabBrowser = getTabBrowser(win);
  818. if ( tabBrowser === null ) {
  819. continue;
  820. }
  821. for ( tab of tabBrowser.tabs ) {
  822. if ( vAPI.fennec || !tab.hasAttribute('pending') ) {
  823. tabIdFromTarget(tab);
  824. }
  825. }
  826. }
  827. Services.ww.registerNotification(windowWatcher);
  828. };
  829. var stop = function() {
  830. Services.ww.unregisterNotification(windowWatcher);
  831. for ( var win of vAPI.tabs.getWindows() ) {
  832. onWindowUnload.call(win);
  833. }
  834. browserToTabIdMap.clear();
  835. tabIdToBrowserMap.clear();
  836. };
  837. cleanupTasks.push(stop);
  838. return {
  839. browsers: function() { return browserToTabIdMap.keys(); },
  840. browserFromTabId: browserFromTabId,
  841. browserFromTarget: browserFromTarget,
  842. currentBrowser: currentBrowser,
  843. indexFromTarget: indexFromTarget,
  844. start: start,
  845. tabFromBrowser: tabFromBrowser,
  846. tabIdFromTarget: tabIdFromTarget
  847. };
  848. })();
  849. /******************************************************************************/
  850. vAPI.setIcon = function(tabId, iconId, badge) {
  851. // If badge is undefined, then setIcon was called from the TabSelect event
  852. var win;
  853. if ( badge === undefined ) {
  854. win = iconId;
  855. } else {
  856. win = Services.wm.getMostRecentWindow('navigator:browser');
  857. }
  858. var curTabId = tabWatcher.tabIdFromTarget(getTabBrowser(win).selectedTab);
  859. var tb = vAPI.toolbarButton;
  860. // from 'TabSelect' event
  861. if ( tabId === undefined ) {
  862. tabId = curTabId;
  863. } else if ( badge !== undefined ) {
  864. tb.tabs[tabId] = { badge: badge, img: iconId };
  865. }
  866. if ( tabId === curTabId ) {
  867. tb.updateState(win, tabId);
  868. }
  869. };
  870. /******************************************************************************/
  871. vAPI.messaging = {
  872. get globalMessageManager() {
  873. return Cc['@mozilla.org/globalmessagemanager;1']
  874. .getService(Ci.nsIMessageListenerManager);
  875. },
  876. frameScript: vAPI.getURL('frameScript.js'),
  877. listeners: {},
  878. defaultHandler: null,
  879. NOOPFUNC: function(){},
  880. UNHANDLED: 'vAPI.messaging.notHandled'
  881. };
  882. /******************************************************************************/
  883. vAPI.messaging.listen = function(listenerName, callback) {
  884. this.listeners[listenerName] = callback;
  885. };
  886. /******************************************************************************/
  887. vAPI.messaging.onMessage = function({target, data}) {
  888. var messageManager = target.messageManager;
  889. if ( !messageManager ) {
  890. // Message came from a popup, and its message manager is not usable.
  891. // So instead we broadcast to the parent window.
  892. messageManager = getOwnerWindow(
  893. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  894. ).messageManager;
  895. }
  896. var channelNameRaw = data.channelName;
  897. var pos = channelNameRaw.indexOf('|');
  898. var channelName = channelNameRaw.slice(pos + 1);
  899. var callback = vAPI.messaging.NOOPFUNC;
  900. if ( data.requestId !== undefined ) {
  901. callback = CallbackWrapper.factory(
  902. messageManager,
  903. channelName,
  904. channelNameRaw.slice(0, pos),
  905. data.requestId
  906. ).callback;
  907. }
  908. var sender = {
  909. tab: {
  910. id: tabWatcher.tabIdFromTarget(target)
  911. }
  912. };
  913. // Specific handler
  914. var r = vAPI.messaging.UNHANDLED;
  915. var listener = vAPI.messaging.listeners[channelName];
  916. if ( typeof listener === 'function' ) {
  917. r = listener(data.msg, sender, callback);
  918. }
  919. if ( r !== vAPI.messaging.UNHANDLED ) {
  920. return;
  921. }
  922. // Default handler
  923. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  924. if ( r !== vAPI.messaging.UNHANDLED ) {
  925. return;
  926. }
  927. console.error('uMatrix> messaging > unknown request: %o', data);
  928. // Unhandled:
  929. // Need to callback anyways in case caller expected an answer, or
  930. // else there is a memory leak on caller's side
  931. callback();
  932. };
  933. /******************************************************************************/
  934. vAPI.messaging.setup = function(defaultHandler) {
  935. // Already setup?
  936. if ( this.defaultHandler !== null ) {
  937. return;
  938. }
  939. if ( typeof defaultHandler !== 'function' ) {
  940. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  941. }
  942. this.defaultHandler = defaultHandler;
  943. this.globalMessageManager.addMessageListener(
  944. location.host + ':background',
  945. this.onMessage
  946. );
  947. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  948. cleanupTasks.push(function() {
  949. var gmm = vAPI.messaging.globalMessageManager;
  950. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  951. gmm.removeMessageListener(
  952. location.host + ':background',
  953. vAPI.messaging.onMessage
  954. );
  955. });
  956. };
  957. /******************************************************************************/
  958. vAPI.messaging.broadcast = function(message) {
  959. this.globalMessageManager.broadcastAsyncMessage(
  960. location.host + ':broadcast',
  961. JSON.stringify({broadcast: true, msg: message})
  962. );
  963. };
  964. /******************************************************************************/
  965. // This allows to avoid creating a closure for every single message which
  966. // expects an answer. Having a closure created each time a message is processed
  967. // has been always bothering me. Another benefit of the implementation here
  968. // is to reuse the callback proxy object, so less memory churning.
  969. //
  970. // https://developers.google.com/speed/articles/optimizing-javascript
  971. // "Creating a closure is significantly slower then creating an inner
  972. // function without a closure, and much slower than reusing a static
  973. // function"
  974. //
  975. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  976. // "the dreaded 'uniformly slow code' case where every function takes 1%
  977. // of CPU and you have to make one hundred separate performance optimizations
  978. // to improve performance at all"
  979. //
  980. // http://jsperf.com/closure-no-closure/2
  981. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  982. this.callback = this.proxy.bind(this); // bind once
  983. this.init(messageManager, channelName, listenerId, requestId);
  984. };
  985. CallbackWrapper.junkyard = [];
  986. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  987. var wrapper = CallbackWrapper.junkyard.pop();
  988. if ( wrapper ) {
  989. wrapper.init(messageManager, channelName, listenerId, requestId);
  990. return wrapper;
  991. }
  992. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  993. };
  994. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  995. this.messageManager = messageManager;
  996. this.channelName = channelName;
  997. this.listenerId = listenerId;
  998. this.requestId = requestId;
  999. };
  1000. CallbackWrapper.prototype.proxy = function(response) {
  1001. var message = JSON.stringify({
  1002. requestId: this.requestId,
  1003. channelName: this.channelName,
  1004. msg: response !== undefined ? response : null
  1005. });
  1006. if ( this.messageManager.sendAsyncMessage ) {
  1007. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1008. } else {
  1009. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1010. }
  1011. // Mark for reuse
  1012. this.messageManager =
  1013. this.channelName =
  1014. this.requestId =
  1015. this.listenerId = null;
  1016. CallbackWrapper.junkyard.push(this);
  1017. };
  1018. /******************************************************************************/
  1019. var httpRequestHeadersFactory = function(channel) {
  1020. var entry = httpRequestHeadersFactory.junkyard.pop();
  1021. if ( entry ) {
  1022. return entry.init(channel);
  1023. }
  1024. return new HTTPRequestHeaders(channel);
  1025. };
  1026. httpRequestHeadersFactory.junkyard = [];
  1027. var HTTPRequestHeaders = function(channel) {
  1028. this.init(channel);
  1029. };
  1030. HTTPRequestHeaders.prototype.init = function(channel) {
  1031. this.channel = channel;
  1032. return this;
  1033. };
  1034. HTTPRequestHeaders.prototype.dispose = function() {
  1035. this.channel = null;
  1036. httpRequestHeadersFactory.junkyard.push(this);
  1037. };
  1038. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1039. try {
  1040. return this.channel.getRequestHeader(name);
  1041. } catch (e) {
  1042. }
  1043. return '';
  1044. };
  1045. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1046. var oldValue = this.getHeader(name);
  1047. if ( newValue === oldValue ) {
  1048. return false;
  1049. }
  1050. if ( oldValue === '' && create !== true ) {
  1051. return false;
  1052. }
  1053. this.channel.setRequestHeader(name, newValue, false);
  1054. return true;
  1055. };
  1056. /******************************************************************************/
  1057. var httpObserver = {
  1058. classDescription: 'net-channel-event-sinks for ' + location.host,
  1059. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1060. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1061. REQDATAKEY: location.host + 'reqdata',
  1062. ABORT: Components.results.NS_BINDING_ABORTED,
  1063. ACCEPT: Components.results.NS_SUCCEEDED,
  1064. // Request types:
  1065. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1066. frameTypeMap: {
  1067. 6: 'main_frame',
  1068. 7: 'sub_frame'
  1069. },
  1070. typeMap: {
  1071. 1: 'other',
  1072. 2: 'script',
  1073. 3: 'image',
  1074. 4: 'stylesheet',
  1075. 5: 'object',
  1076. 6: 'main_frame',
  1077. 7: 'sub_frame',
  1078. 10: 'ping',
  1079. 11: 'xmlhttprequest',
  1080. 12: 'object',
  1081. 14: 'font',
  1082. 15: 'media',
  1083. 16: 'websocket',
  1084. 21: 'image'
  1085. },
  1086. mimeTypeMap: {
  1087. 'audio': 15,
  1088. 'video': 15
  1089. },
  1090. get componentRegistrar() {
  1091. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1092. },
  1093. get categoryManager() {
  1094. return Cc['@mozilla.org/categorymanager;1']
  1095. .getService(Ci.nsICategoryManager);
  1096. },
  1097. QueryInterface: (function() {
  1098. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1099. return XPCOMUtils.generateQI([
  1100. Ci.nsIFactory,
  1101. Ci.nsIObserver,
  1102. Ci.nsIChannelEventSink,
  1103. Ci.nsISupportsWeakReference
  1104. ]);
  1105. })(),
  1106. createInstance: function(outer, iid) {
  1107. if ( outer ) {
  1108. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1109. }
  1110. return this.QueryInterface(iid);
  1111. },
  1112. register: function() {
  1113. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1114. Services.obs.addObserver(this, 'http-on-opening-request', true);
  1115. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1116. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1117. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1118. // Guard against stale instances not having been unregistered
  1119. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1120. try {
  1121. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1122. } catch (ex) {
  1123. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1124. }
  1125. }
  1126. this.componentRegistrar.registerFactory(
  1127. this.classID,
  1128. this.classDescription,
  1129. this.contractID,
  1130. this
  1131. );
  1132. this.categoryManager.addCategoryEntry(
  1133. 'net-channel-event-sinks',
  1134. this.contractID,
  1135. this.contractID,
  1136. false,
  1137. true
  1138. );
  1139. },
  1140. unregister: function() {
  1141. Services.obs.removeObserver(this, 'http-on-opening-request');
  1142. Services.obs.removeObserver(this, 'http-on-modify-request');
  1143. Services.obs.removeObserver(this, 'http-on-examine-response');
  1144. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1145. this.componentRegistrar.unregisterFactory(this.classID, this);
  1146. this.categoryManager.deleteCategoryEntry(
  1147. 'net-channel-event-sinks',
  1148. this.contractID,
  1149. false
  1150. );
  1151. },
  1152. handleRequest: function(channel, URI, tabId, rawtype) {
  1153. var type = this.typeMap[rawtype] || 'other';
  1154. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1155. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  1156. return false;
  1157. }
  1158. var result = onBeforeRequest.callback({
  1159. hostname: URI.asciiHost,
  1160. parentFrameId: type === 'main_frame' ? -1 : 0,
  1161. tabId: tabId,
  1162. type: type,
  1163. url: URI.asciiSpec
  1164. });
  1165. if ( typeof result !== 'object' ) {
  1166. return false;
  1167. }
  1168. channel.cancel(this.ABORT);
  1169. return true;
  1170. },
  1171. handleRequestHeaders: function(channel, URI, tabId, rawtype) {
  1172. var type = this.typeMap[rawtype] || 'other';
  1173. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1174. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  1175. return;
  1176. }
  1177. var requestHeaders = httpRequestHeadersFactory(channel);
  1178. onBeforeSendHeaders.callback({
  1179. hostname: URI.asciiHost,
  1180. parentFrameId: type === 'main_frame' ? -1 : 0,
  1181. requestHeaders: requestHeaders,
  1182. tabId: tabId,
  1183. type: type,
  1184. url: URI.asciiSpec
  1185. });
  1186. requestHeaders.dispose();
  1187. },
  1188. channelDataFromChannel: function(channel) {
  1189. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1190. try {
  1191. return channel.getProperty(this.REQDATAKEY);
  1192. } catch (ex) {
  1193. }
  1194. }
  1195. return null;
  1196. },
  1197. // https://github.com/gorhill/uMatrix/issues/165
  1198. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1199. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1200. // care about embedded frames topography.
  1201. // Also:
  1202. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1203. tabIdFromChannel: function(channel) {
  1204. var aWindow;
  1205. if ( channel.notificationCallbacks ) {
  1206. try {
  1207. var loadContext = channel
  1208. .notificationCallbacks
  1209. .getInterface(Ci.nsILoadContext);
  1210. if ( loadContext.topFrameElement ) {
  1211. return tabWatcher.tabIdFromTarget(loadContext.topFrameElement);
  1212. }
  1213. aWindow = loadContext.associatedWindow;
  1214. } catch (ex) {
  1215. //console.error(ex);
  1216. }
  1217. }
  1218. try {
  1219. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  1220. aWindow = channel
  1221. .loadGroup
  1222. .notificationCallbacks
  1223. .getInterface(Ci.nsILoadContext)
  1224. .associatedWindow;
  1225. }
  1226. if ( aWindow ) {
  1227. return tabWatcher.tabIdFromTarget(
  1228. aWindow
  1229. .getInterface(Ci.nsIWebNavigation)
  1230. .QueryInterface(Ci.nsIDocShell)
  1231. .rootTreeItem
  1232. .QueryInterface(Ci.nsIInterfaceRequestor)
  1233. .getInterface(Ci.nsIDOMWindow)
  1234. .gBrowser
  1235. .getBrowserForContentWindow(aWindow)
  1236. );
  1237. }
  1238. } catch (ex) {
  1239. //console.error(ex);
  1240. }
  1241. return vAPI.noTabId;
  1242. },
  1243. rawtypeFromContentType: function(channel) {
  1244. var mime = channel.contentType;
  1245. if ( !mime ) {
  1246. return 0;
  1247. }
  1248. var pos = mime.indexOf('/');
  1249. if ( pos === -1 ) {
  1250. pos = mime.length;
  1251. }
  1252. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1253. },
  1254. observe: function(channel, topic) {
  1255. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1256. return;
  1257. }
  1258. var URI = channel.URI;
  1259. var channelData, tabId, rawtype;
  1260. if (
  1261. topic === 'http-on-examine-response' ||
  1262. topic === 'http-on-examine-cached-response'
  1263. ) {
  1264. channelData = this.channelDataFromChannel(channel);
  1265. if ( channelData === null ) {
  1266. return;
  1267. }
  1268. var type = this.frameTypeMap[channelData[1]];
  1269. if ( !type ) {
  1270. return;
  1271. }
  1272. topic = 'Content-Security-Policy';
  1273. var result;
  1274. try {
  1275. result = channel.getResponseHeader(topic);
  1276. } catch (ex) {
  1277. result = null;
  1278. }
  1279. result = vAPI.net.onHeadersReceived.callback({
  1280. hostname: URI.asciiHost,
  1281. parentFrameId: type === 'main_frame' ? -1 : 0,
  1282. responseHeaders: result ? [{name: topic, value: result}] : [],
  1283. tabId: channelData[0],
  1284. type: type,
  1285. url: URI.asciiSpec
  1286. });
  1287. if ( result ) {
  1288. channel.setResponseHeader(
  1289. topic,
  1290. result.responseHeaders.pop().value,
  1291. true
  1292. );
  1293. }
  1294. return;
  1295. }
  1296. if ( topic === 'http-on-modify-request' ) {
  1297. channelData = this.channelDataFromChannel(channel);
  1298. if ( channelData === null ) {
  1299. return;
  1300. }
  1301. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1302. return;
  1303. }
  1304. // http-on-opening-request
  1305. tabId = this.tabIdFromChannel(channel);
  1306. rawtype = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1307. if ( this.handleRequest(channel, URI, tabId, rawtype) === true ) {
  1308. return;
  1309. }
  1310. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1311. return;
  1312. }
  1313. // Carry data for behind-the-scene redirects
  1314. channel.setProperty(this.REQDATAKEY, [tabId, rawtype]);
  1315. },
  1316. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1317. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1318. var result = this.ACCEPT;
  1319. // If error thrown, the redirect will fail
  1320. try {
  1321. var URI = newChannel.URI;
  1322. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1323. return;
  1324. }
  1325. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1326. return;
  1327. }
  1328. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1329. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1330. result = this.ABORT;
  1331. return;
  1332. }
  1333. // Carry the data on in case of multiple redirects
  1334. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1335. newChannel.setProperty(this.REQDATAKEY, channelData);
  1336. }
  1337. } catch (ex) {
  1338. // console.error(ex);
  1339. } finally {
  1340. callback.onRedirectVerifyCallback(result);
  1341. }
  1342. }
  1343. };
  1344. /******************************************************************************/
  1345. vAPI.net = {};
  1346. /******************************************************************************/
  1347. vAPI.net.registerListeners = function() {
  1348. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1349. new Set(this.onBeforeRequest.types) :
  1350. null;
  1351. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1352. new Set(this.onBeforeSendHeaders.types) :
  1353. null;
  1354. httpObserver.register();
  1355. cleanupTasks.push(function() {
  1356. httpObserver.unregister();
  1357. });
  1358. };
  1359. /******************************************************************************/
  1360. vAPI.toolbarButton = {
  1361. id: location.host + '-button',
  1362. type: 'view',
  1363. viewId: location.host + '-panel',
  1364. label: vAPI.app.name,
  1365. tooltiptext: vAPI.app.name,
  1366. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1367. };
  1368. /******************************************************************************/
  1369. // Toolbar button UI for desktop Firefox
  1370. vAPI.toolbarButton.init = function() {
  1371. var CustomizableUI;
  1372. try {
  1373. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1374. } catch (ex) {
  1375. return;
  1376. }
  1377. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1378. this.styleURI = [
  1379. '#' + this.id + ' {',
  1380. 'list-style-image: url(',
  1381. vAPI.getURL('img/browsericons/icon19-off.png'),
  1382. ');',
  1383. '}',
  1384. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1385. 'width: 160px;',
  1386. 'height: 290px;',
  1387. 'overflow: hidden !important;',
  1388. '}'
  1389. ];
  1390. var platformVersion = Services.appinfo.platformVersion;
  1391. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1392. this.styleURI.push(
  1393. '#' + this.id + '[badge]:not([badge=""])::after {',
  1394. 'position: absolute;',
  1395. 'margin-left: -16px;',
  1396. 'margin-top: 3px;',
  1397. 'padding: 1px 2px;',
  1398. 'font-size: 9px;',
  1399. 'font-weight: bold;',
  1400. 'color: #fff;',
  1401. 'background: #000;',
  1402. 'content: attr(badge);',
  1403. '}'
  1404. );
  1405. } else {
  1406. this.CUIEvents = {};
  1407. var updateBadge = function() {
  1408. var wId = vAPI.toolbarButton.id;
  1409. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1410. for ( var win of vAPI.tabs.getWindows() ) {
  1411. var button = win.document.getElementById(wId);
  1412. if ( buttonInPanel ) {
  1413. button.classList.remove('badged-button');
  1414. continue;
  1415. }
  1416. if ( button === null ) {
  1417. continue;
  1418. }
  1419. button.classList.add('badged-button');
  1420. }
  1421. if ( buttonInPanel ) {
  1422. return;
  1423. }
  1424. // Anonymous elements need some time to be reachable
  1425. vAPI.setTimeout(this.updateBadgeStyle, 250);
  1426. }.bind(this.CUIEvents);
  1427. this.CUIEvents.onCustomizeEnd = updateBadge;
  1428. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1429. this.CUIEvents.updateBadgeStyle = function() {
  1430. var css = [
  1431. 'background: #000',
  1432. 'color: #fff'
  1433. ].join(';');
  1434. for ( var win of vAPI.tabs.getWindows() ) {
  1435. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1436. if ( button === null ) {
  1437. continue;
  1438. }
  1439. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1440. button,
  1441. 'class',
  1442. 'toolbarbutton-badge'
  1443. );
  1444. if ( !badge ) {
  1445. return;
  1446. }
  1447. badge.style.cssText = css;
  1448. }
  1449. };
  1450. this.onCreated = function(button) {
  1451. button.setAttribute('badge', '');
  1452. vAPI.setTimeout(updateBadge, 250);
  1453. };
  1454. CustomizableUI.addListener(this.CUIEvents);
  1455. }
  1456. this.styleURI = Services.io.newURI(
  1457. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1458. null,
  1459. null
  1460. );
  1461. this.closePopup = function({target}) {
  1462. CustomizableUI.hidePanelForNode(
  1463. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1464. );
  1465. };
  1466. CustomizableUI.createWidget(this);
  1467. vAPI.messaging.globalMessageManager.addMessageListener(
  1468. location.host + ':closePopup',
  1469. this.closePopup
  1470. );
  1471. cleanupTasks.push(function() {
  1472. if ( this.CUIEvents ) {
  1473. CustomizableUI.removeListener(this.CUIEvents);
  1474. }
  1475. CustomizableUI.destroyWidget(this.id);
  1476. vAPI.messaging.globalMessageManager.removeMessageListener(
  1477. location.host + ':closePopup',
  1478. this.closePopup
  1479. );
  1480. for ( var win of vAPI.tabs.getWindows() ) {
  1481. var panel = win.document.getElementById(this.viewId);
  1482. panel.parentNode.removeChild(panel);
  1483. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1484. .getInterface(Ci.nsIDOMWindowUtils)
  1485. .removeSheet(this.styleURI, 1);
  1486. }
  1487. }.bind(this));
  1488. this.init = null;
  1489. };
  1490. /******************************************************************************/
  1491. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1492. var panel = doc.createElement('panelview');
  1493. panel.setAttribute('id', this.viewId);
  1494. var iframe = doc.createElement('iframe');
  1495. iframe.setAttribute('type', 'content');
  1496. iframe.setAttribute('overflow-x', 'hidden');
  1497. doc.getElementById('PanelUI-multiView')
  1498. .appendChild(panel)
  1499. .appendChild(iframe);
  1500. var scrollBarWidth = 0;
  1501. var updateTimer = null;
  1502. var delayedResize = function() {
  1503. if ( updateTimer ) {
  1504. return;
  1505. }
  1506. updateTimer = vAPI.setTimeout(resizePopup, 10);
  1507. };
  1508. var resizePopup = function() {
  1509. updateTimer = null;
  1510. var body = iframe.contentDocument.body;
  1511. panel.parentNode.style.maxWidth = 'none';
  1512. // We set a limit for height
  1513. var height = Math.min(body.clientHeight, 600);
  1514. // https://github.com/chrisaljoudi/uBlock/issues/730
  1515. // Voodoo programming: this recipe works
  1516. panel.style.setProperty('height', height + 'px');
  1517. iframe.style.setProperty('height', height + 'px');
  1518. // Adjust width for presence/absence of vertical scroll bar which may
  1519. // have appeared as a result of last operation.
  1520. var contentWindow = iframe.contentWindow;
  1521. var width = body.clientWidth;
  1522. if ( contentWindow.scrollMaxY !== 0 ) {
  1523. width += scrollBarWidth;
  1524. }
  1525. panel.style.setProperty('width', width + 'px');
  1526. // scrollMaxX should always be zero once we know the scrollbar width
  1527. if ( contentWindow.scrollMaxX !== 0 ) {
  1528. scrollBarWidth = contentWindow.scrollMaxX;
  1529. width += scrollBarWidth;
  1530. panel.style.setProperty('width', width + 'px');
  1531. }
  1532. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1533. delayedResize();
  1534. return;
  1535. }
  1536. };
  1537. var onPopupReady = function() {
  1538. var win = this.contentWindow;
  1539. if ( !win || win.location.host !== location.host ) {
  1540. return;
  1541. }
  1542. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1543. attributes: true,
  1544. characterData: true,
  1545. subtree: true
  1546. });
  1547. delayedResize();
  1548. };
  1549. iframe.addEventListener('load', onPopupReady, true);
  1550. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1551. .getInterface(Ci.nsIDOMWindowUtils)
  1552. .loadSheet(this.styleURI, 1);
  1553. };
  1554. /******************************************************************************/
  1555. vAPI.toolbarButton.onViewShowing = function({target}) {
  1556. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1557. };
  1558. /******************************************************************************/
  1559. vAPI.toolbarButton.onViewHiding = function({target}) {
  1560. target.parentNode.style.maxWidth = '';
  1561. target.firstChild.setAttribute('src', 'about:blank');
  1562. };
  1563. /******************************************************************************/
  1564. vAPI.toolbarButton.updateState = function(win, tabId) {
  1565. var button = win.document.getElementById(this.id);
  1566. if ( !button ) {
  1567. return;
  1568. }
  1569. var icon = this.tabs[tabId];
  1570. button.setAttribute('badge', icon && icon.badge || '');
  1571. var iconId = icon && icon.img ? icon.img : 'off';
  1572. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1573. button.style.listStyleImage = icon;
  1574. };
  1575. /******************************************************************************/
  1576. vAPI.toolbarButton.init();
  1577. /******************************************************************************/
  1578. /******************************************************************************/
  1579. vAPI.contextMenu = {
  1580. contextMap: {
  1581. frame: 'inFrame',
  1582. link: 'onLink',
  1583. image: 'onImage',
  1584. audio: 'onAudio',
  1585. video: 'onVideo',
  1586. editable: 'onEditableArea'
  1587. }
  1588. };
  1589. /******************************************************************************/
  1590. vAPI.contextMenu.displayMenuItem = function({target}) {
  1591. var doc = target.ownerDocument;
  1592. var gContextMenu = doc.defaultView.gContextMenu;
  1593. if ( !gContextMenu.browser ) {
  1594. return;
  1595. }
  1596. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1597. var currentURI = gContextMenu.browser.currentURI;
  1598. // https://github.com/chrisaljoudi/uBlock/issues/105
  1599. // TODO: Should the element picker works on any kind of pages?
  1600. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1601. menuitem.hidden = true;
  1602. return;
  1603. }
  1604. var ctx = vAPI.contextMenu.contexts;
  1605. if ( !ctx ) {
  1606. menuitem.hidden = false;
  1607. return;
  1608. }
  1609. var ctxMap = vAPI.contextMenu.contextMap;
  1610. for ( var context of ctx ) {
  1611. if (
  1612. context === 'page' &&
  1613. !gContextMenu.onLink &&
  1614. !gContextMenu.onImage &&
  1615. !gContextMenu.onEditableArea &&
  1616. !gContextMenu.inFrame &&
  1617. !gContextMenu.onVideo &&
  1618. !gContextMenu.onAudio
  1619. ) {
  1620. menuitem.hidden = false;
  1621. return;
  1622. }
  1623. if ( gContextMenu[ctxMap[context]] ) {
  1624. menuitem.hidden = false;
  1625. return;
  1626. }
  1627. }
  1628. menuitem.hidden = true;
  1629. };
  1630. /******************************************************************************/
  1631. vAPI.contextMenu.register = function(doc) {
  1632. if ( !this.menuItemId ) {
  1633. return;
  1634. }
  1635. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1636. var menuitem = doc.createElement('menuitem');
  1637. menuitem.setAttribute('id', this.menuItemId);
  1638. menuitem.setAttribute('label', this.menuLabel);
  1639. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1640. menuitem.setAttribute('class', 'menuitem-iconic');
  1641. menuitem.addEventListener('command', this.onCommand);
  1642. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1643. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1644. };
  1645. /******************************************************************************/
  1646. vAPI.contextMenu.unregister = function(doc) {
  1647. if ( !this.menuItemId ) {
  1648. return;
  1649. }
  1650. var menuitem = doc.getElementById(this.menuItemId);
  1651. var contextMenu = menuitem.parentNode;
  1652. menuitem.removeEventListener('command', this.onCommand);
  1653. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1654. contextMenu.removeChild(menuitem);
  1655. };
  1656. /******************************************************************************/
  1657. vAPI.contextMenu.create = function(details, callback) {
  1658. this.menuItemId = details.id;
  1659. this.menuLabel = details.title;
  1660. this.contexts = details.contexts;
  1661. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1662. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1663. } else {
  1664. // default in Chrome
  1665. this.contexts = ['page'];
  1666. }
  1667. this.onCommand = function() {
  1668. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1669. var details = {
  1670. menuItemId: this.id
  1671. };
  1672. if ( gContextMenu.inFrame ) {
  1673. details.tagName = 'iframe';
  1674. // Probably won't work with e10s
  1675. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1676. } else if ( gContextMenu.onImage ) {
  1677. details.tagName = 'img';
  1678. details.srcUrl = gContextMenu.mediaURL;
  1679. } else if ( gContextMenu.onAudio ) {
  1680. details.tagName = 'audio';
  1681. details.srcUrl = gContextMenu.mediaURL;
  1682. } else if ( gContextMenu.onVideo ) {
  1683. details.tagName = 'video';
  1684. details.srcUrl = gContextMenu.mediaURL;
  1685. } else if ( gContextMenu.onLink ) {
  1686. details.tagName = 'a';
  1687. details.linkUrl = gContextMenu.linkURL;
  1688. }
  1689. callback(details, {
  1690. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  1691. url: gContextMenu.browser.currentURI.asciiSpec
  1692. });
  1693. };
  1694. for ( var win of vAPI.tabs.getWindows() ) {
  1695. this.register(win.document);
  1696. }
  1697. };
  1698. /******************************************************************************/
  1699. vAPI.contextMenu.remove = function() {
  1700. for ( var win of vAPI.tabs.getWindows() ) {
  1701. this.unregister(win.document);
  1702. }
  1703. this.menuItemId = null;
  1704. this.menuLabel = null;
  1705. this.contexts = null;
  1706. this.onCommand = null;
  1707. };
  1708. /******************************************************************************/
  1709. /******************************************************************************/
  1710. var optionsObserver = {
  1711. addonId: 'uMatrix@raymondhill.net',
  1712. register: function() {
  1713. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1714. cleanupTasks.push(this.unregister.bind(this));
  1715. var browser = tabWatcher.currentBrowser();
  1716. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1717. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1718. }
  1719. },
  1720. unregister: function() {
  1721. Services.obs.removeObserver(this, 'addon-options-displayed');
  1722. },
  1723. setupOptionsButton: function(doc, id, page) {
  1724. var button = doc.getElementById(id);
  1725. if ( button === null ) {
  1726. return;
  1727. }
  1728. button.addEventListener('command', function() {
  1729. vAPI.tabs.open({ url: page, index: -1 });
  1730. });
  1731. button.label = vAPI.i18n(id);
  1732. },
  1733. observe: function(doc, topic, addonId) {
  1734. if ( addonId !== this.addonId ) {
  1735. return;
  1736. }
  1737. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1738. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  1739. }
  1740. };
  1741. optionsObserver.register();
  1742. /******************************************************************************/
  1743. /******************************************************************************/
  1744. vAPI.lastError = function() {
  1745. return null;
  1746. };
  1747. /******************************************************************************/
  1748. /******************************************************************************/
  1749. // This is called only once, when everything has been loaded in memory after
  1750. // the extension was launched. It can be used to inject content scripts
  1751. // in already opened web pages, to remove whatever nuisance could make it to
  1752. // the web pages before uBlock was ready.
  1753. vAPI.onLoadAllCompleted = function() {
  1754. for ( var browser of tabWatcher.browsers() ) {
  1755. browser.messageManager.sendAsyncMessage(
  1756. location.host + '-load-completed'
  1757. );
  1758. }
  1759. };
  1760. /******************************************************************************/
  1761. /******************************************************************************/
  1762. // Likelihood is that we do not have to punycode: given punycode overhead,
  1763. // it's faster to check and skip than do it unconditionally all the time.
  1764. var punycodeHostname = punycode.toASCII;
  1765. var isNotASCII = /[^\x21-\x7F]/;
  1766. vAPI.punycodeHostname = function(hostname) {
  1767. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1768. };
  1769. vAPI.punycodeURL = function(url) {
  1770. if ( isNotASCII.test(url) ) {
  1771. return Services.io.newURI(url, null, null).asciiSpec;
  1772. }
  1773. return url;
  1774. };
  1775. /******************************************************************************/
  1776. /******************************************************************************/
  1777. vAPI.browserData = {};
  1778. /******************************************************************************/
  1779. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  1780. vAPI.browserData.clearCache = function(callback) {
  1781. // PURGE_DISK_DATA_ONLY:1
  1782. // PURGE_DISK_ALL:2
  1783. // PURGE_EVERYTHING:3
  1784. // However I verified that not argument does clear the cache data.
  1785. Services.cache2.clear();
  1786. if ( typeof callback === 'function' ) {
  1787. callback();
  1788. }
  1789. };
  1790. /******************************************************************************/
  1791. vAPI.browserData.clearOrigin = function(/* domain */) {
  1792. // TODO
  1793. };
  1794. /******************************************************************************/
  1795. /******************************************************************************/
  1796. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  1797. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  1798. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  1799. vAPI.cookies = {};
  1800. /******************************************************************************/
  1801. vAPI.cookies.CookieEntry = function(ffCookie) {
  1802. this.domain = ffCookie.host;
  1803. this.name = ffCookie.name;
  1804. this.path = ffCookie.path;
  1805. this.secure = ffCookie.isSecure === true;
  1806. this.session = ffCookie.expires === 0;
  1807. this.value = ffCookie.value;
  1808. };
  1809. /******************************************************************************/
  1810. vAPI.cookies.start = function() {
  1811. Services.obs.addObserver(this, 'cookie-changed', false);
  1812. Services.obs.addObserver(this, 'private-cookie-changed', false);
  1813. cleanupTasks.push(this.stop.bind(this));
  1814. };
  1815. /******************************************************************************/
  1816. vAPI.cookies.stop = function() {
  1817. Services.obs.removeObserver(this, 'cookie-changed');
  1818. Services.obs.removeObserver(this, 'private-cookie-changed');
  1819. };
  1820. /******************************************************************************/
  1821. vAPI.cookies.observe = function(subject, topic, reason) {
  1822. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  1823. // return;
  1824. //}
  1825. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  1826. return;
  1827. }
  1828. if ( typeof this.onChanged === 'function' ) {
  1829. this.onChanged(new this.CookieEntry(subject));
  1830. }
  1831. };
  1832. /******************************************************************************/
  1833. // Meant and expected to be asynchronous.
  1834. vAPI.cookies.getAll = function(callback) {
  1835. if ( typeof callback !== 'function' ) {
  1836. return;
  1837. }
  1838. var onAsync = function() {
  1839. var out = [];
  1840. var enumerator = Services.cookies.enumerator;
  1841. var ffcookie;
  1842. while ( enumerator.hasMoreElements() ) {
  1843. ffcookie = enumerator.getNext();
  1844. if ( ffcookie instanceof Ci.nsICookie ) {
  1845. out.push(new this.CookieEntry(ffcookie));
  1846. }
  1847. }
  1848. callback(out);
  1849. };
  1850. vAPI.setTimeout(onAsync.bind(this), 0);
  1851. };
  1852. /******************************************************************************/
  1853. vAPI.cookies.remove = function(details, callback) {
  1854. var uri = Services.io.newURI(details.url, null, null);
  1855. var cookies = Services.cookies;
  1856. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  1857. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  1858. if ( typeof callback === 'function' ) {
  1859. callback({
  1860. domain: uri.asciiHost,
  1861. name: details.name,
  1862. path: uri.path
  1863. });
  1864. }
  1865. };
  1866. /******************************************************************************/
  1867. /******************************************************************************/
  1868. })();
  1869. /******************************************************************************/