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.

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