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.

2954 lines
90 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 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. vAPI.firefoxPre35 = Services.vc.compare(Services.appinfo.platformVersion, '35.0') < 0;
  34. /******************************************************************************/
  35. vAPI.app = {
  36. name: 'uMatrix',
  37. version: location.hash.slice(1)
  38. };
  39. /******************************************************************************/
  40. vAPI.app.start = function() {
  41. };
  42. /******************************************************************************/
  43. vAPI.app.stop = function() {
  44. };
  45. /******************************************************************************/
  46. vAPI.app.restart = function() {
  47. // Listening in bootstrap.js
  48. Cc['@mozilla.org/childprocessmessagemanager;1']
  49. .getService(Ci.nsIMessageSender)
  50. .sendAsyncMessage(location.host + '-restart');
  51. };
  52. /******************************************************************************/
  53. // https://stackoverflow.com/questions/6715571/how-to-get-result-of-console-trace-as-string-in-javascript-with-chrome-or-fire/28118170#28118170
  54. /*
  55. function logStackTrace(msg) {
  56. var stack;
  57. try {
  58. throw new Error('');
  59. }
  60. catch (error) {
  61. stack = error.stack || '';
  62. }
  63. stack = stack.split('\n').map(function(line) { return line.trim(); });
  64. stack.shift();
  65. if ( msg ) {
  66. stack.unshift(msg);
  67. }
  68. console.log(stack.join('\n'));
  69. }
  70. */
  71. /******************************************************************************/
  72. // List of things that needs to be destroyed when disabling the extension
  73. // Only functions should be added to it
  74. var cleanupTasks = [];
  75. // This must be updated manually, every time a new task is added/removed
  76. // Fixed by github.com/AlexVallat:
  77. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  78. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  79. var expectedNumberOfCleanups = 7;
  80. window.addEventListener('unload', function() {
  81. if ( typeof vAPI.app.onShutdown === 'function' ) {
  82. vAPI.app.onShutdown();
  83. }
  84. for ( var cleanup of cleanupTasks ) {
  85. cleanup();
  86. }
  87. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  88. console.error(
  89. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  90. cleanupTasks.length,
  91. expectedNumberOfCleanups
  92. );
  93. }
  94. // frameModule needs to be cleared too
  95. var frameModule = {};
  96. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  97. frameModule.contentObserver.unregister();
  98. Cu.unload(vAPI.getURL('frameModule.js'));
  99. });
  100. /******************************************************************************/
  101. // For now, only booleans.
  102. vAPI.browserSettings = {
  103. originalValues: {},
  104. rememberOriginalValue: function(branch, setting) {
  105. var key = branch + '.' + setting;
  106. if ( this.originalValues.hasOwnProperty(key) ) {
  107. return;
  108. }
  109. var hasUserValue = false;
  110. try {
  111. hasUserValue = Services.prefs.getBranch(branch + '.').prefHasUserValue(setting);
  112. } catch (ex) {
  113. }
  114. this.originalValues[key] = hasUserValue ? this.getBool(branch, setting) : undefined;
  115. },
  116. clear: function(branch, setting) {
  117. var key = branch + '.' + setting;
  118. // Value was not overriden -- nothing to restore
  119. if ( this.originalValues.hasOwnProperty(key) === false ) {
  120. return;
  121. }
  122. var value = this.originalValues[key];
  123. // https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979
  124. // Forget the value immediately, it may change outside of
  125. // uBlock control.
  126. delete this.originalValues[key];
  127. // Original value was a default one
  128. if ( value === undefined ) {
  129. try {
  130. Services.prefs.getBranch(branch + '.').clearUserPref(setting);
  131. } catch (ex) {
  132. }
  133. return;
  134. }
  135. // Current value is same as original
  136. if ( this.getBool(branch, setting) === value ) {
  137. return;
  138. }
  139. // Reset to original value
  140. try {
  141. Services.prefs.getBranch(branch + '.').setBoolPref(setting, value);
  142. } catch (ex) {
  143. }
  144. },
  145. getBool: function(branch, setting) {
  146. try {
  147. return Services.prefs.getBranch(branch + '.').getBoolPref(setting);
  148. } catch (ex) {
  149. }
  150. return undefined;
  151. },
  152. setBool: function(branch, setting, value) {
  153. try {
  154. Services.prefs.getBranch(branch + '.').setBoolPref(setting, value);
  155. } catch (ex) {
  156. }
  157. },
  158. set: function(details) {
  159. var value;
  160. for ( var setting in details ) {
  161. if ( details.hasOwnProperty(setting) === false ) {
  162. continue;
  163. }
  164. switch ( setting ) {
  165. case 'prefetching':
  166. this.rememberOriginalValue('network', 'prefetch-next');
  167. value = !!details[setting];
  168. // https://github.com/gorhill/uBlock/issues/292
  169. // "true" means "do not disable", i.e. leave entry alone
  170. if ( value === true ) {
  171. this.clear('network', 'prefetch-next');
  172. } else {
  173. this.setBool('network', 'prefetch-next', false);
  174. }
  175. break;
  176. case 'hyperlinkAuditing':
  177. this.rememberOriginalValue('browser', 'send_pings');
  178. this.rememberOriginalValue('beacon', 'enabled');
  179. value = !!details[setting];
  180. // https://github.com/gorhill/uBlock/issues/292
  181. // "true" means "do not disable", i.e. leave entry alone
  182. if ( value === true ) {
  183. this.clear('browser', 'send_pings');
  184. this.clear('beacon', 'enabled');
  185. } else {
  186. this.setBool('browser', 'send_pings', false);
  187. this.setBool('beacon', 'enabled', false);
  188. }
  189. break;
  190. case 'webrtcIPAddress':
  191. this.rememberOriginalValue('media.peerconnection', 'enabled');
  192. value = !!details[setting];
  193. if ( value === true ) {
  194. this.clear('media.peerconnection', 'enabled');
  195. } else {
  196. this.setBool('media.peerconnection', 'enabled', false);
  197. }
  198. break;
  199. default:
  200. break;
  201. }
  202. }
  203. },
  204. restoreAll: function() {
  205. var pos;
  206. for ( var key in this.originalValues ) {
  207. if ( this.originalValues.hasOwnProperty(key) === false ) {
  208. continue;
  209. }
  210. pos = key.lastIndexOf('.');
  211. this.clear(key.slice(0, pos), key.slice(pos + 1));
  212. }
  213. }
  214. };
  215. cleanupTasks.push(vAPI.browserSettings.restoreAll.bind(vAPI.browserSettings));
  216. /******************************************************************************/
  217. // API matches that of chrome.storage.local:
  218. // https://developer.chrome.com/extensions/storage
  219. vAPI.storage = (function() {
  220. var db = null;
  221. var vacuumTimer = null;
  222. var close = function() {
  223. if ( vacuumTimer !== null ) {
  224. clearTimeout(vacuumTimer);
  225. vacuumTimer = null;
  226. }
  227. if ( db === null ) {
  228. return;
  229. }
  230. db.asyncClose();
  231. db = null;
  232. };
  233. var open = function() {
  234. if ( db !== null ) {
  235. return db;
  236. }
  237. // Create path
  238. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  239. path.append('extension-data');
  240. if ( !path.exists() ) {
  241. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  242. }
  243. if ( !path.isDirectory() ) {
  244. throw Error('Should be a directory...');
  245. }
  246. path.append(location.host + '.sqlite');
  247. // Open database
  248. try {
  249. db = Services.storage.openDatabase(path);
  250. if ( db.connectionReady === false ) {
  251. db.asyncClose();
  252. db = null;
  253. }
  254. } catch (ex) {
  255. }
  256. if ( db === null ) {
  257. return null;
  258. }
  259. // Database was opened, register cleanup task
  260. cleanupTasks.push(close);
  261. // Setup database
  262. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
  263. .executeAsync();
  264. if ( vacuum !== null ) {
  265. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  266. }
  267. return db;
  268. };
  269. // https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
  270. // Vacuum only once, and only while idle
  271. var vacuum = function() {
  272. vacuumTimer = null;
  273. if ( db === null ) {
  274. return;
  275. }
  276. var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
  277. .getService(Ci.nsIIdleService);
  278. if ( idleSvc.idleTime < 60000 ) {
  279. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  280. return;
  281. }
  282. db.createAsyncStatement('VACUUM').executeAsync();
  283. vacuum = null;
  284. };
  285. // Execute a query
  286. var runStatement = function(stmt, callback) {
  287. var result = {};
  288. stmt.executeAsync({
  289. handleResult: function(rows) {
  290. if ( !rows || typeof callback !== 'function' ) {
  291. return;
  292. }
  293. var row;
  294. while ( row = rows.getNextRow() ) {
  295. // we assume that there will be two columns, since we're
  296. // using it only for preferences
  297. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  298. }
  299. },
  300. handleCompletion: function(reason) {
  301. if ( typeof callback === 'function' && reason === 0 ) {
  302. callback(result);
  303. }
  304. },
  305. handleError: function(error) {
  306. console.error('SQLite error ', error.result, error.message);
  307. // Caller expects an answer regardless of failure.
  308. if ( typeof callback === 'function' ) {
  309. callback(null);
  310. }
  311. }
  312. });
  313. };
  314. var bindNames = function(stmt, names) {
  315. if ( Array.isArray(names) === false || names.length === 0 ) {
  316. return;
  317. }
  318. var params = stmt.newBindingParamsArray();
  319. var i = names.length, bp;
  320. while ( i-- ) {
  321. bp = params.newBindingParams();
  322. bp.bindByName('name', names[i]);
  323. params.addParams(bp);
  324. }
  325. stmt.bindParameters(params);
  326. };
  327. var clear = function(callback) {
  328. if ( open() === null ) {
  329. if ( typeof callback === 'function' ) {
  330. callback();
  331. }
  332. return;
  333. }
  334. runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
  335. };
  336. var getBytesInUse = function(keys, callback) {
  337. if ( typeof callback !== 'function' ) {
  338. return;
  339. }
  340. if ( open() === null ) {
  341. callback(0);
  342. return;
  343. }
  344. var stmt;
  345. if ( Array.isArray(keys) ) {
  346. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
  347. bindNames(keys);
  348. } else {
  349. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
  350. }
  351. runStatement(stmt, function(result) {
  352. callback(result.size);
  353. });
  354. };
  355. var read = function(details, callback) {
  356. if ( typeof callback !== 'function' ) {
  357. return;
  358. }
  359. var prepareResult = function(result) {
  360. var key;
  361. for ( key in result ) {
  362. if ( result.hasOwnProperty(key) === false ) {
  363. continue;
  364. }
  365. result[key] = JSON.parse(result[key]);
  366. }
  367. if ( typeof details === 'object' && details !== null ) {
  368. for ( key in details ) {
  369. if ( result.hasOwnProperty(key) === false ) {
  370. result[key] = details[key];
  371. }
  372. }
  373. }
  374. callback(result);
  375. };
  376. if ( open() === null ) {
  377. prepareResult({});
  378. return;
  379. }
  380. var names = [];
  381. if ( details !== null ) {
  382. if ( Array.isArray(details) ) {
  383. names = details;
  384. } else if ( typeof details === 'object' ) {
  385. names = Object.keys(details);
  386. } else {
  387. names = [details.toString()];
  388. }
  389. }
  390. var stmt;
  391. if ( names.length === 0 ) {
  392. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  393. } else {
  394. stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
  395. bindNames(stmt, names);
  396. }
  397. runStatement(stmt, prepareResult);
  398. };
  399. var remove = function(keys, callback) {
  400. if ( open() === null ) {
  401. if ( typeof callback === 'function' ) {
  402. callback();
  403. }
  404. return;
  405. }
  406. var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
  407. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  408. runStatement(stmt, callback);
  409. };
  410. var write = function(details, callback) {
  411. if ( open() === null ) {
  412. if ( typeof callback === 'function' ) {
  413. callback();
  414. }
  415. return;
  416. }
  417. var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
  418. var params = stmt.newBindingParamsArray(), bp;
  419. for ( var key in details ) {
  420. if ( details.hasOwnProperty(key) === false ) {
  421. continue;
  422. }
  423. bp = params.newBindingParams();
  424. bp.bindByName('name', key);
  425. bp.bindByName('value', JSON.stringify(details[key]));
  426. params.addParams(bp);
  427. }
  428. if ( params.length === 0 ) {
  429. return;
  430. }
  431. stmt.bindParameters(params);
  432. runStatement(stmt, callback);
  433. };
  434. // Export API
  435. var api = {
  436. QUOTA_BYTES: 100 * 1024 * 1024,
  437. clear: clear,
  438. get: read,
  439. getBytesInUse: getBytesInUse,
  440. remove: remove,
  441. set: write
  442. };
  443. return api;
  444. })();
  445. /******************************************************************************/
  446. var getTabBrowser = function(win) {
  447. return win.gBrowser || null;
  448. };
  449. /******************************************************************************/
  450. var getOwnerWindow = function(target) {
  451. if ( target.ownerDocument ) {
  452. return target.ownerDocument.defaultView;
  453. }
  454. return null;
  455. };
  456. /******************************************************************************/
  457. vAPI.isBehindTheSceneTabId = function(tabId) {
  458. return tabId.toString() === '-1';
  459. };
  460. vAPI.noTabId = '-1';
  461. /******************************************************************************/
  462. vAPI.tabs = {};
  463. /******************************************************************************/
  464. vAPI.tabs.registerListeners = function() {
  465. tabWatcher.start();
  466. };
  467. /******************************************************************************/
  468. vAPI.tabs.get = function(tabId, callback) {
  469. var browser;
  470. if ( tabId === null ) {
  471. browser = tabWatcher.currentBrowser();
  472. tabId = tabWatcher.tabIdFromTarget(browser);
  473. } else {
  474. browser = tabWatcher.browserFromTabId(tabId);
  475. }
  476. // For internal use
  477. if ( typeof callback !== 'function' ) {
  478. return browser;
  479. }
  480. if ( !browser ) {
  481. callback();
  482. return;
  483. }
  484. var win = getOwnerWindow(browser);
  485. var tabBrowser = getTabBrowser(win);
  486. var windows = this.getWindows();
  487. callback({
  488. id: tabId,
  489. index: tabWatcher.indexFromTarget(browser),
  490. windowId: windows.indexOf(win),
  491. active: browser === tabBrowser.selectedBrowser,
  492. url: browser.currentURI.asciiSpec,
  493. title: browser.contentTitle
  494. });
  495. };
  496. /******************************************************************************/
  497. vAPI.tabs.getAllSync = function(window) {
  498. var win, tab;
  499. var tabs = [];
  500. for ( win of this.getWindows() ) {
  501. if ( window && window !== win ) {
  502. continue;
  503. }
  504. var tabBrowser = getTabBrowser(win);
  505. if ( tabBrowser === null ) {
  506. continue;
  507. }
  508. for ( tab of tabBrowser.tabs ) {
  509. tabs.push(tab);
  510. }
  511. }
  512. return tabs;
  513. };
  514. /******************************************************************************/
  515. vAPI.tabs.getAll = function(callback) {
  516. var tabs = [], tab;
  517. for ( var browser of tabWatcher.browsers() ) {
  518. tab = tabWatcher.tabFromBrowser(browser);
  519. if ( tab === null ) {
  520. continue;
  521. }
  522. if ( tab.hasAttribute('pending') ) {
  523. continue;
  524. }
  525. tabs.push({
  526. id: tabWatcher.tabIdFromTarget(browser),
  527. url: browser.currentURI.asciiSpec
  528. });
  529. }
  530. callback(tabs);
  531. };
  532. /******************************************************************************/
  533. vAPI.tabs.getWindows = function() {
  534. var winumerator = Services.wm.getEnumerator('navigator:browser');
  535. var windows = [];
  536. while ( winumerator.hasMoreElements() ) {
  537. var win = winumerator.getNext();
  538. if ( !win.closed ) {
  539. windows.push(win);
  540. }
  541. }
  542. return windows;
  543. };
  544. /******************************************************************************/
  545. // properties of the details object:
  546. // url: 'URL', // the address that will be opened
  547. // tabId: 1, // the tab is used if set, instead of creating a new one
  548. // index: -1, // undefined: end of the list, -1: following tab, or after index
  549. // active: false, // opens the tab in background - true and undefined: foreground
  550. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  551. vAPI.tabs.open = function(details) {
  552. if ( !details.url ) {
  553. return null;
  554. }
  555. // extension pages
  556. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  557. details.url = vAPI.getURL(details.url);
  558. }
  559. var tab;
  560. if ( details.select ) {
  561. var URI = Services.io.newURI(details.url, null, null);
  562. for ( tab of this.getAllSync() ) {
  563. var browser = tabWatcher.browserFromTarget(tab);
  564. // Or simply .equals if we care about the fragment
  565. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  566. continue;
  567. }
  568. this.select(tab);
  569. return;
  570. }
  571. }
  572. if ( details.active === undefined ) {
  573. details.active = true;
  574. }
  575. if ( details.tabId ) {
  576. tab = tabWatcher.browserFromTabId(details.tabId);
  577. if ( tab ) {
  578. tabWatcher.browserFromTarget(tab).loadURI(details.url);
  579. return;
  580. }
  581. }
  582. var win = Services.wm.getMostRecentWindow('navigator:browser');
  583. var tabBrowser = getTabBrowser(win);
  584. // Open in a standalone window
  585. if ( details.popup === true ) {
  586. Services.ww.openWindow(
  587. self,
  588. details.url,
  589. null,
  590. 'menubar=no,toolbar=no,location=no,resizable=yes',
  591. null
  592. );
  593. return;
  594. }
  595. if ( details.index === -1 ) {
  596. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  597. }
  598. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  599. if ( details.index !== undefined ) {
  600. tabBrowser.moveTabTo(tab, details.index);
  601. }
  602. };
  603. /******************************************************************************/
  604. // Replace the URL of a tab. Noop if the tab does not exist.
  605. vAPI.tabs.replace = function(tabId, url) {
  606. var targetURL = url;
  607. // extension pages
  608. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  609. targetURL = vAPI.getURL(targetURL);
  610. }
  611. var browser = tabWatcher.browserFromTabId(tabId);
  612. if ( browser ) {
  613. browser.loadURI(targetURL);
  614. }
  615. };
  616. /******************************************************************************/
  617. vAPI.tabs._remove = function(tab, tabBrowser) {
  618. tabBrowser.removeTab(tab);
  619. };
  620. /******************************************************************************/
  621. vAPI.tabs.remove = function(tabId) {
  622. var browser = tabWatcher.browserFromTabId(tabId);
  623. if ( !browser ) {
  624. return;
  625. }
  626. var tab = tabWatcher.tabFromBrowser(browser);
  627. if ( !tab ) {
  628. return;
  629. }
  630. this._remove(tab, getTabBrowser(getOwnerWindow(browser)));
  631. };
  632. /******************************************************************************/
  633. vAPI.tabs.reload = function(tabId) {
  634. var browser = tabWatcher.browserFromTabId(tabId);
  635. if ( !browser ) {
  636. return;
  637. }
  638. browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
  639. };
  640. /******************************************************************************/
  641. vAPI.tabs.select = function(tab) {
  642. if ( typeof tab !== 'object' ) {
  643. tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
  644. }
  645. if ( !tab ) {
  646. return;
  647. }
  648. // https://github.com/gorhill/uBlock/issues/470
  649. var win = getOwnerWindow(tab);
  650. win.focus();
  651. var tabBrowser = getTabBrowser(win);
  652. tabBrowser.selectedTab = tab;
  653. };
  654. /******************************************************************************/
  655. vAPI.tabs.injectScript = function(tabId, details, callback) {
  656. var browser = tabWatcher.browserFromTabId(tabId);
  657. if ( !browser ) {
  658. return;
  659. }
  660. if ( typeof details.file !== 'string' ) {
  661. return;
  662. }
  663. details.file = vAPI.getURL(details.file);
  664. browser.messageManager.sendAsyncMessage(
  665. location.host + ':broadcast',
  666. JSON.stringify({
  667. broadcast: true,
  668. channelName: 'vAPI',
  669. msg: {
  670. cmd: 'injectScript',
  671. details: details
  672. }
  673. })
  674. );
  675. if ( typeof callback === 'function' ) {
  676. vAPI.setTimeout(callback, 13);
  677. }
  678. };
  679. /******************************************************************************/
  680. // Firefox:
  681. // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
  682. //
  683. // browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
  684. // ^ |
  685. // | |
  686. // +-------------------------------------------------------------------
  687. //
  688. // browser (browser)
  689. // contentTitle
  690. // currentURI
  691. // ownerDocument (XULDocument)
  692. // defaultView (ChromeWindow)
  693. // gBrowser (tabbrowser OR browser)
  694. // browsers (browser)
  695. // selectedBrowser
  696. // selectedTab
  697. // tabs (tab.tabbrowser-tab)
  698. //
  699. // Fennec: (what I figured so far)
  700. //
  701. // tab --> browser windows --> window --> BrowserApp --> tabs --+
  702. // ^ window |
  703. // | |
  704. // +---------------------------------------------------------------+
  705. //
  706. // tab
  707. // browser
  708. // [manual search to go back to tab from list of windows]
  709. var tabWatcher = (function() {
  710. // TODO: find out whether we need a janitor to take care of stale entries.
  711. var browserToTabIdMap = new Map();
  712. var tabIdToBrowserMap = new Map();
  713. var tabIdGenerator = 1;
  714. var indexFromBrowser = function(browser) {
  715. var win = getOwnerWindow(browser);
  716. if ( !win ) {
  717. return -1;
  718. }
  719. var tabbrowser = getTabBrowser(win);
  720. if ( !tabbrowser ) {
  721. return -1;
  722. }
  723. // This can happen, for example, the `view-source:` window, there is
  724. // no tabbrowser object, the browser object sits directly in the
  725. // window.
  726. if ( tabbrowser === browser ) {
  727. return 0;
  728. }
  729. // Fennec
  730. // https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/BrowserApp
  731. if ( vAPI.fennec ) {
  732. return tabbrowser.tabs.indexOf(tabbrowser.getTabForBrowser(browser));
  733. }
  734. return tabbrowser.browsers.indexOf(browser);
  735. };
  736. var indexFromTarget = function(target) {
  737. return indexFromBrowser(browserFromTarget(target));
  738. };
  739. var tabFromBrowser = function(browser) {
  740. var i = indexFromBrowser(browser);
  741. if ( i === -1 ) {
  742. return null;
  743. }
  744. var win = getOwnerWindow(browser);
  745. if ( !win ) {
  746. return null;
  747. }
  748. var tabbrowser = getTabBrowser(win);
  749. if ( !tabbrowser ) {
  750. return null;
  751. }
  752. if ( !tabbrowser.tabs || i >= tabbrowser.tabs.length ) {
  753. return null;
  754. }
  755. return tabbrowser.tabs[i];
  756. };
  757. var browserFromTarget = function(target) {
  758. if ( !target ) {
  759. return null;
  760. }
  761. if ( vAPI.fennec ) {
  762. if ( target.browser ) { // target is a tab
  763. target = target.browser;
  764. }
  765. } else if ( target.linkedPanel ) { // target is a tab
  766. target = target.linkedBrowser;
  767. }
  768. if ( target.localName !== 'browser' ) {
  769. return null;
  770. }
  771. return target;
  772. };
  773. var tabIdFromTarget = function(target) {
  774. var browser = browserFromTarget(target);
  775. if ( browser === null ) {
  776. return vAPI.noTabId;
  777. }
  778. var tabId = browserToTabIdMap.get(browser);
  779. if ( tabId === undefined ) {
  780. tabId = '' + tabIdGenerator++;
  781. browserToTabIdMap.set(browser, tabId);
  782. tabIdToBrowserMap.set(tabId, browser);
  783. }
  784. return tabId;
  785. };
  786. var browserFromTabId = function(tabId) {
  787. var browser = tabIdToBrowserMap.get(tabId);
  788. if ( browser === undefined ) {
  789. return null;
  790. }
  791. // Verify that the browser is still live
  792. if ( indexFromBrowser(browser) !== -1 ) {
  793. return browser;
  794. }
  795. removeBrowserEntry(tabId, browser);
  796. return null;
  797. };
  798. var currentBrowser = function() {
  799. var win = Services.wm.getMostRecentWindow('navigator:browser');
  800. // https://github.com/gorhill/uBlock/issues/399
  801. // getTabBrowser() can return null at browser launch time.
  802. var tabBrowser = getTabBrowser(win);
  803. if ( tabBrowser === null ) {
  804. return null;
  805. }
  806. return browserFromTarget(tabBrowser.selectedTab);
  807. };
  808. var removeBrowserEntry = function(tabId, browser) {
  809. if ( tabId && tabId !== vAPI.noTabId ) {
  810. vAPI.tabs.onClosed(tabId);
  811. delete vAPI.toolbarButton.tabs[tabId];
  812. tabIdToBrowserMap.delete(tabId);
  813. }
  814. if ( browser ) {
  815. browserToTabIdMap.delete(browser);
  816. }
  817. };
  818. // https://developer.mozilla.org/en-US/docs/Web/Events/TabOpen
  819. var onOpen = function({target}) {
  820. var tabId = tabIdFromTarget(target);
  821. var browser = browserFromTabId(tabId);
  822. vAPI.tabs.onNavigation({
  823. frameId: 0,
  824. tabId: tabId,
  825. url: browser.currentURI.asciiSpec,
  826. });
  827. };
  828. // https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
  829. var onShow = function({target}) {
  830. tabIdFromTarget(target);
  831. };
  832. // https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
  833. var onClose = function({target}) {
  834. // target is tab in Firefox, browser in Fennec
  835. var browser = browserFromTarget(target);
  836. var tabId = browserToTabIdMap.get(browser);
  837. removeBrowserEntry(tabId, browser);
  838. };
  839. // https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
  840. var onSelect = function({target}) {
  841. vAPI.setIcon(tabIdFromTarget(target), getOwnerWindow(target));
  842. };
  843. var locationChangedMessageName = location.host + ':locationChanged';
  844. var onLocationChanged = function(e) {
  845. var vapi = vAPI;
  846. var details = e.data;
  847. // Ignore notifications related to our popup
  848. if ( details.url.lastIndexOf(vapi.getURL('popup.html'), 0) === 0 ) {
  849. return;
  850. }
  851. var browser = e.target;
  852. var tabId = tabIdFromTarget(browser);
  853. if ( tabId === vapi.noTabId ) {
  854. return;
  855. }
  856. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  857. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  858. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  859. vapi.tabs.onUpdated(tabId, {url: details.url}, {
  860. frameId: 0,
  861. tabId: tabId,
  862. url: browser.currentURI.asciiSpec
  863. });
  864. return;
  865. }
  866. // https://github.com/chrisaljoudi/uBlock/issues/105
  867. // Allow any kind of pages
  868. vapi.tabs.onNavigation({
  869. frameId: 0,
  870. tabId: tabId,
  871. url: details.url,
  872. });
  873. };
  874. var attachToTabBrowser = function(window) {
  875. var tabBrowser = getTabBrowser(window);
  876. if ( !tabBrowser ) {
  877. return false;
  878. }
  879. var tabContainer = tabBrowser.tabContainer;
  880. if ( !tabContainer ) {
  881. return true;
  882. }
  883. vAPI.contextMenu.register(window.document);
  884. if ( typeof vAPI.toolbarButton.attachToNewWindow === 'function' ) {
  885. vAPI.toolbarButton.attachToNewWindow(window);
  886. }
  887. tabContainer.addEventListener('TabOpen', onOpen);
  888. tabContainer.addEventListener('TabShow', onShow);
  889. tabContainer.addEventListener('TabClose', onClose);
  890. tabContainer.addEventListener('TabSelect', onSelect);
  891. return true;
  892. };
  893. var onWindowLoad = function(ev) {
  894. if ( ev ) {
  895. this.removeEventListener(ev.type, onWindowLoad);
  896. }
  897. var wintype = this.document.documentElement.getAttribute('windowtype');
  898. if ( wintype !== 'navigator:browser' ) {
  899. return;
  900. }
  901. // On some platforms, the tab browser isn't immediately available,
  902. // try waiting a bit if this happens.
  903. var win = this;
  904. if ( attachToTabBrowser(win) === false ) {
  905. vAPI.setTimeout(attachToTabBrowser.bind(null, win), 250);
  906. }
  907. };
  908. var onWindowUnload = function() {
  909. vAPI.contextMenu.unregister(this.document);
  910. this.removeEventListener('DOMContentLoaded', onWindowLoad);
  911. var tabBrowser = getTabBrowser(this);
  912. if ( !tabBrowser ) {
  913. return;
  914. }
  915. var tabContainer = null;
  916. if ( tabBrowser.tabContainer ) {
  917. tabContainer = tabBrowser.tabContainer;
  918. }
  919. if ( tabContainer ) {
  920. tabContainer.removeEventListener('TabOpen', onOpen);
  921. tabContainer.removeEventListener('TabShow', onShow);
  922. tabContainer.removeEventListener('TabClose', onClose);
  923. tabContainer.removeEventListener('TabSelect', onSelect);
  924. }
  925. var browser, URI, tabId;
  926. for ( var tab of tabBrowser.tabs ) {
  927. browser = tabWatcher.browserFromTarget(tab);
  928. if ( browser === null ) {
  929. continue;
  930. }
  931. URI = browser.currentURI;
  932. // Close extension tabs
  933. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  934. vAPI.tabs._remove(tab, getTabBrowser(this));
  935. }
  936. browser = browserFromTarget(tab);
  937. tabId = browserToTabIdMap.get(browser);
  938. if ( tabId !== undefined ) {
  939. removeBrowserEntry(tabId, browser);
  940. tabIdToBrowserMap.delete(tabId);
  941. }
  942. browserToTabIdMap.delete(browser);
  943. }
  944. };
  945. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
  946. var windowWatcher = {
  947. observe: function(win, topic) {
  948. if ( topic === 'domwindowopened' ) {
  949. win.addEventListener('DOMContentLoaded', onWindowLoad);
  950. return;
  951. }
  952. if ( topic === 'domwindowclosed' ) {
  953. onWindowUnload.call(win);
  954. return;
  955. }
  956. }
  957. };
  958. // Initialize map with existing active tabs
  959. var start = function() {
  960. var tabBrowser, tab;
  961. for ( var win of vAPI.tabs.getWindows() ) {
  962. onWindowLoad.call(win);
  963. tabBrowser = getTabBrowser(win);
  964. if ( tabBrowser === null ) {
  965. continue;
  966. }
  967. for ( tab of tabBrowser.tabs ) {
  968. if ( vAPI.fennec || !tab.hasAttribute('pending') ) {
  969. tabIdFromTarget(tab);
  970. }
  971. }
  972. }
  973. vAPI.messaging.globalMessageManager.addMessageListener(
  974. locationChangedMessageName,
  975. onLocationChanged
  976. );
  977. Services.ww.registerNotification(windowWatcher);
  978. };
  979. var stop = function() {
  980. vAPI.messaging.globalMessageManager.removeMessageListener(
  981. locationChangedMessageName,
  982. onLocationChanged
  983. );
  984. Services.ww.unregisterNotification(windowWatcher);
  985. for ( var win of vAPI.tabs.getWindows() ) {
  986. onWindowUnload.call(win);
  987. }
  988. browserToTabIdMap.clear();
  989. tabIdToBrowserMap.clear();
  990. };
  991. cleanupTasks.push(stop);
  992. return {
  993. browsers: function() { return browserToTabIdMap.keys(); },
  994. browserFromTabId: browserFromTabId,
  995. browserFromTarget: browserFromTarget,
  996. currentBrowser: currentBrowser,
  997. indexFromTarget: indexFromTarget,
  998. start: start,
  999. tabFromBrowser: tabFromBrowser,
  1000. tabIdFromTarget: tabIdFromTarget
  1001. };
  1002. })();
  1003. /******************************************************************************/
  1004. vAPI.setIcon = function(tabId, iconId, badge) {
  1005. // If badge is undefined, then setIcon was called from the TabSelect event
  1006. var win;
  1007. if ( badge === undefined ) {
  1008. win = iconId;
  1009. } else {
  1010. win = Services.wm.getMostRecentWindow('navigator:browser');
  1011. }
  1012. var curTabId = tabWatcher.tabIdFromTarget(getTabBrowser(win).selectedTab);
  1013. var tb = vAPI.toolbarButton;
  1014. // from 'TabSelect' event
  1015. if ( tabId === undefined ) {
  1016. tabId = curTabId;
  1017. } else if ( badge !== undefined ) {
  1018. tb.tabs[tabId] = { badge: badge, img: iconId };
  1019. }
  1020. if ( tabId === curTabId ) {
  1021. tb.updateState(win, tabId);
  1022. }
  1023. };
  1024. /******************************************************************************/
  1025. vAPI.messaging = {
  1026. get globalMessageManager() {
  1027. return Cc['@mozilla.org/globalmessagemanager;1']
  1028. .getService(Ci.nsIMessageListenerManager);
  1029. },
  1030. frameScript: vAPI.getURL('frameScript.js'),
  1031. listeners: {},
  1032. defaultHandler: null,
  1033. NOOPFUNC: function(){},
  1034. UNHANDLED: 'vAPI.messaging.notHandled'
  1035. };
  1036. /******************************************************************************/
  1037. vAPI.messaging.listen = function(listenerName, callback) {
  1038. this.listeners[listenerName] = callback;
  1039. };
  1040. /******************************************************************************/
  1041. vAPI.messaging.onMessage = function({target, data}) {
  1042. var messageManager = target.messageManager;
  1043. if ( !messageManager ) {
  1044. // Message came from a popup, and its message manager is not usable.
  1045. // So instead we broadcast to the parent window.
  1046. messageManager = getOwnerWindow(
  1047. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  1048. ).messageManager;
  1049. }
  1050. var channelNameRaw = data.channelName;
  1051. var pos = channelNameRaw.indexOf('|');
  1052. var channelName = channelNameRaw.slice(pos + 1);
  1053. var callback = vAPI.messaging.NOOPFUNC;
  1054. if ( data.requestId !== undefined ) {
  1055. callback = CallbackWrapper.factory(
  1056. messageManager,
  1057. channelName,
  1058. channelNameRaw.slice(0, pos),
  1059. data.requestId
  1060. ).callback;
  1061. }
  1062. var sender = {
  1063. tab: {
  1064. id: tabWatcher.tabIdFromTarget(target)
  1065. }
  1066. };
  1067. // Specific handler
  1068. var r = vAPI.messaging.UNHANDLED;
  1069. var listener = vAPI.messaging.listeners[channelName];
  1070. if ( typeof listener === 'function' ) {
  1071. r = listener(data.msg, sender, callback);
  1072. }
  1073. if ( r !== vAPI.messaging.UNHANDLED ) {
  1074. return;
  1075. }
  1076. // Default handler
  1077. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  1078. if ( r !== vAPI.messaging.UNHANDLED ) {
  1079. return;
  1080. }
  1081. console.error('uMatrix> messaging > unknown request: %o', data);
  1082. // Unhandled:
  1083. // Need to callback anyways in case caller expected an answer, or
  1084. // else there is a memory leak on caller's side
  1085. callback();
  1086. };
  1087. /******************************************************************************/
  1088. vAPI.messaging.setup = function(defaultHandler) {
  1089. // Already setup?
  1090. if ( this.defaultHandler !== null ) {
  1091. return;
  1092. }
  1093. if ( typeof defaultHandler !== 'function' ) {
  1094. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  1095. }
  1096. this.defaultHandler = defaultHandler;
  1097. this.globalMessageManager.addMessageListener(
  1098. location.host + ':background',
  1099. this.onMessage
  1100. );
  1101. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  1102. cleanupTasks.push(function() {
  1103. var gmm = vAPI.messaging.globalMessageManager;
  1104. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  1105. gmm.removeMessageListener(
  1106. location.host + ':background',
  1107. vAPI.messaging.onMessage
  1108. );
  1109. });
  1110. };
  1111. /******************************************************************************/
  1112. vAPI.messaging.broadcast = function(message) {
  1113. this.globalMessageManager.broadcastAsyncMessage(
  1114. location.host + ':broadcast',
  1115. JSON.stringify({broadcast: true, msg: message})
  1116. );
  1117. };
  1118. /******************************************************************************/
  1119. // This allows to avoid creating a closure for every single message which
  1120. // expects an answer. Having a closure created each time a message is processed
  1121. // has been always bothering me. Another benefit of the implementation here
  1122. // is to reuse the callback proxy object, so less memory churning.
  1123. //
  1124. // https://developers.google.com/speed/articles/optimizing-javascript
  1125. // "Creating a closure is significantly slower then creating an inner
  1126. // function without a closure, and much slower than reusing a static
  1127. // function"
  1128. //
  1129. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  1130. // "the dreaded 'uniformly slow code' case where every function takes 1%
  1131. // of CPU and you have to make one hundred separate performance optimizations
  1132. // to improve performance at all"
  1133. //
  1134. // http://jsperf.com/closure-no-closure/2
  1135. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  1136. this.callback = this.proxy.bind(this); // bind once
  1137. this.init(messageManager, channelName, listenerId, requestId);
  1138. };
  1139. CallbackWrapper.junkyard = [];
  1140. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  1141. var wrapper = CallbackWrapper.junkyard.pop();
  1142. if ( wrapper ) {
  1143. wrapper.init(messageManager, channelName, listenerId, requestId);
  1144. return wrapper;
  1145. }
  1146. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  1147. };
  1148. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  1149. this.messageManager = messageManager;
  1150. this.channelName = channelName;
  1151. this.listenerId = listenerId;
  1152. this.requestId = requestId;
  1153. };
  1154. CallbackWrapper.prototype.proxy = function(response) {
  1155. var message = JSON.stringify({
  1156. requestId: this.requestId,
  1157. channelName: this.channelName,
  1158. msg: response !== undefined ? response : null
  1159. });
  1160. if ( this.messageManager.sendAsyncMessage ) {
  1161. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1162. } else {
  1163. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1164. }
  1165. // Mark for reuse
  1166. this.messageManager =
  1167. this.channelName =
  1168. this.requestId =
  1169. this.listenerId = null;
  1170. CallbackWrapper.junkyard.push(this);
  1171. };
  1172. /******************************************************************************/
  1173. var httpRequestHeadersFactory = function(channel) {
  1174. var entry = httpRequestHeadersFactory.junkyard.pop();
  1175. if ( entry ) {
  1176. return entry.init(channel);
  1177. }
  1178. return new HTTPRequestHeaders(channel);
  1179. };
  1180. httpRequestHeadersFactory.junkyard = [];
  1181. var HTTPRequestHeaders = function(channel) {
  1182. this.init(channel);
  1183. };
  1184. HTTPRequestHeaders.prototype.init = function(channel) {
  1185. this.channel = channel;
  1186. return this;
  1187. };
  1188. HTTPRequestHeaders.prototype.dispose = function() {
  1189. this.channel = null;
  1190. httpRequestHeadersFactory.junkyard.push(this);
  1191. };
  1192. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1193. try {
  1194. return this.channel.getRequestHeader(name);
  1195. } catch (e) {
  1196. }
  1197. return '';
  1198. };
  1199. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1200. var oldValue = this.getHeader(name);
  1201. if ( newValue === oldValue ) {
  1202. return false;
  1203. }
  1204. if ( oldValue === '' && create !== true ) {
  1205. return false;
  1206. }
  1207. this.channel.setRequestHeader(name, newValue, false);
  1208. return true;
  1209. };
  1210. /******************************************************************************/
  1211. var httpObserver = {
  1212. classDescription: 'net-channel-event-sinks for ' + location.host,
  1213. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1214. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1215. REQDATAKEY: location.host + 'reqdata',
  1216. ABORT: Components.results.NS_BINDING_ABORTED,
  1217. ACCEPT: Components.results.NS_SUCCEEDED,
  1218. // Request types:
  1219. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1220. frameTypeMap: {
  1221. 6: 'main_frame',
  1222. 7: 'sub_frame'
  1223. },
  1224. typeMap: {
  1225. 1: 'other',
  1226. 2: 'script',
  1227. 3: 'image',
  1228. 4: 'stylesheet',
  1229. 5: 'object',
  1230. 6: 'main_frame',
  1231. 7: 'sub_frame',
  1232. 10: 'ping',
  1233. 11: 'xmlhttprequest',
  1234. 12: 'object',
  1235. 14: 'font',
  1236. 15: 'media',
  1237. 16: 'websocket',
  1238. 21: 'image'
  1239. },
  1240. mimeTypeMap: {
  1241. 'audio': 15,
  1242. 'video': 15
  1243. },
  1244. get componentRegistrar() {
  1245. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1246. },
  1247. get categoryManager() {
  1248. return Cc['@mozilla.org/categorymanager;1']
  1249. .getService(Ci.nsICategoryManager);
  1250. },
  1251. QueryInterface: (function() {
  1252. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1253. return XPCOMUtils.generateQI([
  1254. Ci.nsIFactory,
  1255. Ci.nsIObserver,
  1256. Ci.nsIChannelEventSink,
  1257. Ci.nsISupportsWeakReference
  1258. ]);
  1259. })(),
  1260. createInstance: function(outer, iid) {
  1261. if ( outer ) {
  1262. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1263. }
  1264. return this.QueryInterface(iid);
  1265. },
  1266. register: function() {
  1267. this.pendingRingBufferInit();
  1268. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1269. Services.obs.addObserver(this, 'http-on-opening-request', true);
  1270. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1271. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1272. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1273. // Guard against stale instances not having been unregistered
  1274. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1275. try {
  1276. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1277. } catch (ex) {
  1278. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1279. }
  1280. }
  1281. this.componentRegistrar.registerFactory(
  1282. this.classID,
  1283. this.classDescription,
  1284. this.contractID,
  1285. this
  1286. );
  1287. this.categoryManager.addCategoryEntry(
  1288. 'net-channel-event-sinks',
  1289. this.contractID,
  1290. this.contractID,
  1291. false,
  1292. true
  1293. );
  1294. },
  1295. unregister: function() {
  1296. Services.obs.removeObserver(this, 'http-on-opening-request');
  1297. Services.obs.removeObserver(this, 'http-on-modify-request');
  1298. Services.obs.removeObserver(this, 'http-on-examine-response');
  1299. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1300. this.componentRegistrar.unregisterFactory(this.classID, this);
  1301. this.categoryManager.deleteCategoryEntry(
  1302. 'net-channel-event-sinks',
  1303. this.contractID,
  1304. false
  1305. );
  1306. },
  1307. PendingRequest: function() {
  1308. this.rawType = 0;
  1309. this.tabId = 0;
  1310. this._key = ''; // key is url, from URI.spec
  1311. },
  1312. // If all work fine, this map should not grow indefinitely. It can have
  1313. // stale items in it, but these will be taken care of when entries in
  1314. // the ring buffer are overwritten.
  1315. pendingURLToIndex: new Map(),
  1316. pendingWritePointer: 0,
  1317. pendingRingBuffer: new Array(32),
  1318. pendingRingBufferInit: function() {
  1319. // Use and reuse pre-allocated PendingRequest objects = less memory
  1320. // churning.
  1321. var i = this.pendingRingBuffer.length;
  1322. while ( i-- ) {
  1323. this.pendingRingBuffer[i] = new this.PendingRequest();
  1324. }
  1325. },
  1326. createPendingRequest: function(url) {
  1327. var bucket;
  1328. var i = this.pendingWritePointer;
  1329. this.pendingWritePointer = i + 1 & 31;
  1330. var preq = this.pendingRingBuffer[i];
  1331. // Cleanup unserviced pending request
  1332. if ( preq._key !== '' ) {
  1333. bucket = this.pendingURLToIndex.get(preq._key);
  1334. if ( Array.isArray(bucket) ) {
  1335. // Assuming i in array
  1336. var pos = bucket.indexOf(i);
  1337. bucket.splice(pos, 1);
  1338. if ( bucket.length === 1 ) {
  1339. this.pendingURLToIndex.set(preq._key, bucket[0]);
  1340. }
  1341. } else if ( typeof bucket === 'number' ) {
  1342. // Assuming bucket === i
  1343. this.pendingURLToIndex.delete(preq._key);
  1344. }
  1345. }
  1346. // Would be much simpler if a url could not appear more than once.
  1347. bucket = this.pendingURLToIndex.get(url);
  1348. if ( bucket === undefined ) {
  1349. this.pendingURLToIndex.set(url, i);
  1350. } else if ( Array.isArray(bucket) ) {
  1351. bucket = bucket.push(i);
  1352. } else {
  1353. bucket = [bucket, i];
  1354. }
  1355. preq._key = url;
  1356. return preq;
  1357. },
  1358. lookupPendingRequest: function(url) {
  1359. var i = this.pendingURLToIndex.get(url);
  1360. if ( i === undefined ) {
  1361. return null;
  1362. }
  1363. if ( Array.isArray(i) ) {
  1364. var bucket = i;
  1365. i = bucket.shift();
  1366. if ( bucket.length === 1 ) {
  1367. this.pendingURLToIndex.set(url, bucket[0]);
  1368. }
  1369. } else {
  1370. this.pendingURLToIndex.delete(url);
  1371. }
  1372. var preq = this.pendingRingBuffer[i];
  1373. preq._key = ''; // mark as "serviced"
  1374. return preq;
  1375. },
  1376. handleRequest: function(channel, URI, tabId, rawType) {
  1377. var type = this.typeMap[rawType] || 'other';
  1378. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1379. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  1380. return false;
  1381. }
  1382. var result = onBeforeRequest.callback({
  1383. hostname: URI.asciiHost,
  1384. parentFrameId: type === 'main_frame' ? -1 : 0,
  1385. tabId: tabId,
  1386. type: type,
  1387. url: URI.asciiSpec
  1388. });
  1389. if ( typeof result !== 'object' ) {
  1390. return false;
  1391. }
  1392. channel.cancel(this.ABORT);
  1393. return true;
  1394. },
  1395. handleRequestHeaders: function(channel, URI, tabId, rawType) {
  1396. var type = this.typeMap[rawType] || 'other';
  1397. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1398. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  1399. return;
  1400. }
  1401. var requestHeaders = httpRequestHeadersFactory(channel);
  1402. onBeforeSendHeaders.callback({
  1403. hostname: URI.asciiHost,
  1404. parentFrameId: type === 'main_frame' ? -1 : 0,
  1405. requestHeaders: requestHeaders,
  1406. tabId: tabId,
  1407. type: type,
  1408. url: URI.asciiSpec
  1409. });
  1410. requestHeaders.dispose();
  1411. },
  1412. channelDataFromChannel: function(channel) {
  1413. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1414. try {
  1415. return channel.getProperty(this.REQDATAKEY);
  1416. } catch (ex) {
  1417. }
  1418. }
  1419. return null;
  1420. },
  1421. // https://github.com/gorhill/uMatrix/issues/165
  1422. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1423. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1424. // care about embedded frames topography.
  1425. // Also:
  1426. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1427. tabIdFromChannel: function(channel) {
  1428. var aWindow;
  1429. if ( channel.notificationCallbacks ) {
  1430. try {
  1431. var loadContext = channel
  1432. .notificationCallbacks
  1433. .getInterface(Ci.nsILoadContext);
  1434. if ( loadContext.topFrameElement ) {
  1435. return tabWatcher.tabIdFromTarget(loadContext.topFrameElement);
  1436. }
  1437. aWindow = loadContext.associatedWindow;
  1438. } catch (ex) {
  1439. //console.error(ex);
  1440. }
  1441. }
  1442. try {
  1443. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  1444. aWindow = channel
  1445. .loadGroup
  1446. .notificationCallbacks
  1447. .getInterface(Ci.nsILoadContext)
  1448. .associatedWindow;
  1449. }
  1450. if ( aWindow ) {
  1451. return tabWatcher.tabIdFromTarget(
  1452. aWindow
  1453. .getInterface(Ci.nsIWebNavigation)
  1454. .QueryInterface(Ci.nsIDocShell)
  1455. .rootTreeItem
  1456. .QueryInterface(Ci.nsIInterfaceRequestor)
  1457. .getInterface(Ci.nsIDOMWindow)
  1458. .gBrowser
  1459. .getBrowserForContentWindow(aWindow)
  1460. );
  1461. }
  1462. } catch (ex) {
  1463. //console.error(ex);
  1464. }
  1465. return vAPI.noTabId;
  1466. },
  1467. rawtypeFromContentType: function(channel) {
  1468. var mime = channel.contentType;
  1469. if ( !mime ) {
  1470. return 0;
  1471. }
  1472. var pos = mime.indexOf('/');
  1473. if ( pos === -1 ) {
  1474. pos = mime.length;
  1475. }
  1476. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1477. },
  1478. observe: function(channel, topic) {
  1479. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1480. return;
  1481. }
  1482. var URI = channel.URI;
  1483. var channelData;
  1484. if (
  1485. topic === 'http-on-examine-response' ||
  1486. topic === 'http-on-examine-cached-response'
  1487. ) {
  1488. channelData = this.channelDataFromChannel(channel);
  1489. if ( channelData === null ) {
  1490. return;
  1491. }
  1492. var type = this.frameTypeMap[channelData[1]];
  1493. if ( !type ) {
  1494. return;
  1495. }
  1496. topic = 'Content-Security-Policy';
  1497. var result;
  1498. try {
  1499. result = channel.getResponseHeader(topic);
  1500. } catch (ex) {
  1501. result = null;
  1502. }
  1503. result = vAPI.net.onHeadersReceived.callback({
  1504. hostname: URI.asciiHost,
  1505. parentFrameId: type === 'main_frame' ? -1 : 0,
  1506. responseHeaders: result ? [{name: topic, value: result}] : [],
  1507. tabId: channelData[0],
  1508. type: type,
  1509. url: URI.asciiSpec
  1510. });
  1511. if ( result ) {
  1512. channel.setResponseHeader(
  1513. topic,
  1514. result.responseHeaders.pop().value,
  1515. true
  1516. );
  1517. }
  1518. return;
  1519. }
  1520. if ( topic === 'http-on-modify-request' ) {
  1521. channelData = this.channelDataFromChannel(channel);
  1522. if ( channelData === null ) {
  1523. return;
  1524. }
  1525. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1526. return;
  1527. }
  1528. // http-on-opening-request
  1529. var tabId, rawType;
  1530. var pendingRequest = this.lookupPendingRequest(URI.asciiSpec);
  1531. if ( pendingRequest !== null ) {
  1532. tabId = pendingRequest.tabId;
  1533. rawType = pendingRequest.rawType;
  1534. } else {
  1535. tabId = this.tabIdFromChannel(channel);
  1536. rawType = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1537. }
  1538. if ( this.handleRequest(channel, URI, tabId, rawType) ) {
  1539. return;
  1540. }
  1541. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1542. return;
  1543. }
  1544. // Carry data for behind-the-scene redirects
  1545. channel.setProperty(this.REQDATAKEY, [tabId, rawType]);
  1546. },
  1547. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1548. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1549. var result = this.ACCEPT;
  1550. // If error thrown, the redirect will fail
  1551. try {
  1552. var URI = newChannel.URI;
  1553. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1554. return;
  1555. }
  1556. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1557. return;
  1558. }
  1559. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1560. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1561. result = this.ABORT;
  1562. return;
  1563. }
  1564. // Carry the data on in case of multiple redirects
  1565. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1566. newChannel.setProperty(this.REQDATAKEY, channelData);
  1567. }
  1568. } catch (ex) {
  1569. // console.error(ex);
  1570. } finally {
  1571. callback.onRedirectVerifyCallback(result);
  1572. }
  1573. }
  1574. };
  1575. /******************************************************************************/
  1576. vAPI.net = {};
  1577. /******************************************************************************/
  1578. vAPI.net.registerListeners = function() {
  1579. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1580. new Set(this.onBeforeRequest.types) :
  1581. null;
  1582. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1583. new Set(this.onBeforeSendHeaders.types) :
  1584. null;
  1585. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1586. var shouldLoadListener = function(e) {
  1587. var details = e.data;
  1588. var pendingReq = httpObserver.createPendingRequest(details.url);
  1589. pendingReq.rawType = details.rawType;
  1590. pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
  1591. };
  1592. // https://github.com/gorhill/uMatrix/issues/200
  1593. // We need this only for Firefox 34 and less: the tab id is derived from
  1594. // the origin of the message.
  1595. if ( vAPI.firefoxPre35 ) {
  1596. vAPI.messaging.globalMessageManager.addMessageListener(
  1597. shouldLoadListenerMessageName,
  1598. shouldLoadListener
  1599. );
  1600. }
  1601. httpObserver.register();
  1602. cleanupTasks.push(function() {
  1603. if ( vAPI.firefoxPre35 ) {
  1604. vAPI.messaging.globalMessageManager.removeMessageListener(
  1605. shouldLoadListenerMessageName,
  1606. shouldLoadListener
  1607. );
  1608. }
  1609. httpObserver.unregister();
  1610. });
  1611. };
  1612. /******************************************************************************/
  1613. /******************************************************************************/
  1614. vAPI.toolbarButton = {
  1615. id: location.host + '-button',
  1616. type: 'view',
  1617. viewId: location.host + '-panel',
  1618. label: vAPI.app.name,
  1619. tooltiptext: vAPI.app.name,
  1620. tabs: {/*tabId: {badge: 0, img: boolean}*/},
  1621. init: null,
  1622. codePath: ''
  1623. };
  1624. /******************************************************************************/
  1625. // Non-Fennec: common code paths.
  1626. (function() {
  1627. if ( vAPI.fennec ) {
  1628. return;
  1629. }
  1630. var tbb = vAPI.toolbarButton;
  1631. var popupCommittedWidth = 0;
  1632. var popupCommittedHeight = 0;
  1633. tbb.onViewShowing = function({target}) {
  1634. popupCommittedWidth = popupCommittedHeight = 0;
  1635. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1636. };
  1637. tbb.onViewHiding = function({target}) {
  1638. target.parentNode.style.maxWidth = '';
  1639. target.firstChild.setAttribute('src', 'about:blank');
  1640. };
  1641. tbb.updateState = function(win, tabId) {
  1642. var button = win.document.getElementById(this.id);
  1643. if ( !button ) {
  1644. return;
  1645. }
  1646. var icon = this.tabs[tabId];
  1647. button.setAttribute('badge', icon && icon.badge || '');
  1648. button.classList.toggle('off', !icon || !icon.img);
  1649. var iconId = icon && icon.img ? icon.img : 'off';
  1650. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1651. button.style.listStyleImage = icon;
  1652. };
  1653. tbb.populatePanel = function(doc, panel) {
  1654. panel.setAttribute('id', this.viewId);
  1655. var iframe = doc.createElement('iframe');
  1656. iframe.setAttribute('type', 'content');
  1657. panel.appendChild(iframe);
  1658. var toPx = function(pixels) {
  1659. return pixels.toString() + 'px';
  1660. };
  1661. var scrollBarWidth = 0;
  1662. var resizeTimer = null;
  1663. var resizePopupDelayed = function(attempts) {
  1664. if ( resizeTimer !== null ) {
  1665. return false;
  1666. }
  1667. // Sanity check
  1668. attempts = (attempts || 0) + 1;
  1669. if ( attempts > 1/*000*/ ) {
  1670. //console.error('uMatrix> resizePopupDelayed: giving up after too many attempts');
  1671. return false;
  1672. }
  1673. resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
  1674. return true;
  1675. };
  1676. var resizePopup = function(attempts) {
  1677. resizeTimer = null;
  1678. panel.parentNode.style.maxWidth = 'none';
  1679. var body = iframe.contentDocument.body;
  1680. // https://github.com/gorhill/uMatrix/issues/301
  1681. // Don't resize if committed size did not change.
  1682. if (
  1683. popupCommittedWidth === body.clientWidth &&
  1684. popupCommittedHeight === body.clientHeight
  1685. ) {
  1686. return;
  1687. }
  1688. // We set a limit for height
  1689. var height = Math.min(body.clientHeight, 600);
  1690. // https://github.com/chrisaljoudi/uBlock/issues/730
  1691. // Voodoo programming: this recipe works
  1692. panel.style.setProperty('height', toPx(height));
  1693. iframe.style.setProperty('height', toPx(height));
  1694. // Adjust width for presence/absence of vertical scroll bar which may
  1695. // have appeared as a result of last operation.
  1696. var contentWindow = iframe.contentWindow;
  1697. var width = body.clientWidth;
  1698. if ( contentWindow.scrollMaxY !== 0 ) {
  1699. width += scrollBarWidth;
  1700. }
  1701. panel.style.setProperty('width', toPx(width));
  1702. // scrollMaxX should always be zero once we know the scrollbar width
  1703. if ( contentWindow.scrollMaxX !== 0 ) {
  1704. scrollBarWidth = contentWindow.scrollMaxX;
  1705. width += scrollBarWidth;
  1706. panel.style.setProperty('width', toPx(width));
  1707. }
  1708. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1709. if ( resizePopupDelayed(attempts) ) {
  1710. return;
  1711. }
  1712. // resizePopupDelayed won't be called again, so commit
  1713. // dimentsions.
  1714. }
  1715. popupCommittedWidth = body.clientWidth;
  1716. popupCommittedHeight = body.clientHeight;
  1717. };
  1718. var onResizeRequested = function() {
  1719. var body = iframe.contentDocument.body;
  1720. if ( body.getAttribute('data-resize-popup') !== 'true' ) {
  1721. return;
  1722. }
  1723. body.removeAttribute('data-resize-popup');
  1724. resizePopupDelayed();
  1725. };
  1726. var onPopupReady = function() {
  1727. var win = this.contentWindow;
  1728. if ( !win || win.location.host !== location.host ) {
  1729. return;
  1730. }
  1731. if ( typeof tbb.onBeforePopupReady === 'function' ) {
  1732. tbb.onBeforePopupReady.call(this);
  1733. }
  1734. resizePopupDelayed();
  1735. var body = win.document.body;
  1736. body.removeAttribute('data-resize-popup');
  1737. var mutationObserver = new win.MutationObserver(onResizeRequested);
  1738. mutationObserver.observe(body, {
  1739. attributes: true,
  1740. attributeFilter: [ 'data-resize-popup' ]
  1741. });
  1742. };
  1743. iframe.addEventListener('load', onPopupReady, true);
  1744. };
  1745. })();
  1746. /******************************************************************************/
  1747. // Firefox 28 and less
  1748. (function() {
  1749. var tbb = vAPI.toolbarButton;
  1750. if ( tbb.init !== null ) {
  1751. return;
  1752. }
  1753. var CustomizableUI = null;
  1754. var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
  1755. if ( !forceLegacyToolbarButton ) {
  1756. try {
  1757. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1758. } catch (ex) {
  1759. }
  1760. }
  1761. if ( CustomizableUI !== null ) {
  1762. return;
  1763. }
  1764. tbb.codePath = 'legacy';
  1765. tbb.id = 'umatrix-legacy-button'; // NOTE: must match legacy-toolbar-button.css
  1766. tbb.viewId = tbb.id + '-panel';
  1767. var sss = null;
  1768. var styleSheetUri = null;
  1769. var addLegacyToolbarButton = function(window) {
  1770. var document = window.document;
  1771. var toolbox = document.getElementById('navigator-toolbox') || document.getElementById('mail-toolbox');
  1772. if ( !toolbox ) {
  1773. return;
  1774. }
  1775. // palette might take a little longer to appear on some platforms,
  1776. // give it a small delay and try again.
  1777. var palette = toolbox.palette;
  1778. if ( !palette ) {
  1779. vAPI.setTimeout(function() {
  1780. if ( toolbox.palette ) {
  1781. addLegacyToolbarButton(window);
  1782. }
  1783. }, 250);
  1784. return;
  1785. }
  1786. var toolbarButton = document.createElement('toolbarbutton');
  1787. toolbarButton.setAttribute('id', tbb.id);
  1788. // type = panel would be more accurate, but doesn't look as good
  1789. toolbarButton.setAttribute('type', 'menu');
  1790. toolbarButton.setAttribute('removable', 'true');
  1791. toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
  1792. toolbarButton.setAttribute('label', tbb.label);
  1793. toolbarButton.setAttribute('tooltiptext', tbb.label);
  1794. var toolbarButtonPanel = document.createElement('panel');
  1795. // NOTE: Setting level to parent breaks the popup for PaleMoon under
  1796. // linux (mouse pointer misaligned with content). For some reason.
  1797. // toolbarButtonPanel.setAttribute('level', 'parent');
  1798. tbb.populatePanel(document, toolbarButtonPanel);
  1799. toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
  1800. toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
  1801. toolbarButton.appendChild(toolbarButtonPanel);
  1802. palette.appendChild(toolbarButton);
  1803. tbb.closePopup = function() {
  1804. toolbarButtonPanel.hidePopup();
  1805. };
  1806. // No button yet so give it a default location. If forcing the button,
  1807. // just put in in the palette rather than on any specific toolbar (who
  1808. // knows what toolbars will be available or visible!)
  1809. var toolbar;
  1810. if ( !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  1811. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  1812. toolbar = document.getElementById('nav-bar');
  1813. if ( toolbar === null ) {
  1814. return;
  1815. }
  1816. // https://github.com/gorhill/uBlock/issues/264
  1817. // Find a child customizable palette, if any.
  1818. toolbar = toolbar.querySelector('.customization-target') || toolbar;
  1819. toolbar.appendChild(toolbarButton);
  1820. toolbar.setAttribute('currentset', toolbar.currentSet);
  1821. document.persist(toolbar.id, 'currentset');
  1822. return;
  1823. }
  1824. // Find the place to put the button
  1825. var toolbars = toolbox.externalToolbars.slice();
  1826. for ( var child of toolbox.children ) {
  1827. if ( child.localName === 'toolbar' ) {
  1828. toolbars.push(child);
  1829. }
  1830. }
  1831. for ( toolbar of toolbars ) {
  1832. var currentsetString = toolbar.getAttribute('currentset');
  1833. if ( !currentsetString ) {
  1834. continue;
  1835. }
  1836. var currentset = currentsetString.split(',');
  1837. var index = currentset.indexOf(tbb.id);
  1838. if ( index === -1 ) {
  1839. continue;
  1840. }
  1841. // Found our button on this toolbar - but where on it?
  1842. var before = null;
  1843. for ( var i = index + 1; i < currentset.length; i++ ) {
  1844. before = document.getElementById(currentset[i]);
  1845. if ( before === null ) {
  1846. continue;
  1847. }
  1848. toolbar.insertItem(tbb.id, before);
  1849. break;
  1850. }
  1851. if ( before === null ) {
  1852. toolbar.insertItem(tbb.id);
  1853. }
  1854. }
  1855. };
  1856. var onPopupCloseRequested = function({target}) {
  1857. if ( typeof tbb.closePopup === 'function' ) {
  1858. tbb.closePopup(target);
  1859. }
  1860. };
  1861. var shutdown = function() {
  1862. for ( var win of vAPI.tabs.getWindows() ) {
  1863. var toolbarButton = win.document.getElementById(tbb.id);
  1864. if ( toolbarButton ) {
  1865. toolbarButton.parentNode.removeChild(toolbarButton);
  1866. }
  1867. }
  1868. if ( sss === null ) {
  1869. return;
  1870. }
  1871. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  1872. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  1873. }
  1874. sss = null;
  1875. styleSheetUri = null;
  1876. vAPI.messaging.globalMessageManager.removeMessageListener(
  1877. location.host + ':closePopup',
  1878. onPopupCloseRequested
  1879. );
  1880. };
  1881. tbb.attachToNewWindow = function(win) {
  1882. addLegacyToolbarButton(win);
  1883. };
  1884. tbb.init = function() {
  1885. vAPI.messaging.globalMessageManager.addMessageListener(
  1886. location.host + ':closePopup',
  1887. onPopupCloseRequested
  1888. );
  1889. sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
  1890. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  1891. // Register global so it works in all windows, including palette
  1892. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  1893. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  1894. }
  1895. cleanupTasks.push(shutdown);
  1896. };
  1897. })();
  1898. /******************************************************************************/
  1899. // Firefox Australis < 36.
  1900. (function() {
  1901. var tbb = vAPI.toolbarButton;
  1902. if ( tbb.init !== null ) {
  1903. return;
  1904. }
  1905. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  1906. return null;
  1907. }
  1908. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  1909. return null;
  1910. }
  1911. var CustomizableUI = null;
  1912. try {
  1913. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1914. } catch (ex) {
  1915. }
  1916. if ( CustomizableUI === null ) {
  1917. return;
  1918. }
  1919. tbb.codePath = 'australis';
  1920. tbb.CustomizableUI = CustomizableUI;
  1921. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  1922. var styleURI = null;
  1923. var onPopupCloseRequested = function({target}) {
  1924. if ( typeof tbb.closePopup === 'function' ) {
  1925. tbb.closePopup(target);
  1926. }
  1927. };
  1928. var shutdown = function() {
  1929. CustomizableUI.destroyWidget(tbb.id);
  1930. for ( var win of vAPI.tabs.getWindows() ) {
  1931. var panel = win.document.getElementById(tbb.viewId);
  1932. panel.parentNode.removeChild(panel);
  1933. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1934. .getInterface(Ci.nsIDOMWindowUtils)
  1935. .removeSheet(styleURI, 1);
  1936. }
  1937. vAPI.messaging.globalMessageManager.removeMessageListener(
  1938. location.host + ':closePopup',
  1939. onPopupCloseRequested
  1940. );
  1941. };
  1942. tbb.onBeforeCreated = function(doc) {
  1943. var panel = doc.createElement('panelview');
  1944. this.populatePanel(doc, panel);
  1945. doc.getElementById('PanelUI-multiView').appendChild(panel);
  1946. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1947. .getInterface(Ci.nsIDOMWindowUtils)
  1948. .loadSheet(styleURI, 1);
  1949. };
  1950. tbb.onBeforePopupReady = function() {
  1951. // https://github.com/gorhill/uBlock/issues/83
  1952. // Add `portrait` class if width is constrained.
  1953. try {
  1954. this.contentDocument.body.classList.toggle(
  1955. 'portrait',
  1956. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  1957. );
  1958. } catch (ex) {
  1959. /* noop */
  1960. }
  1961. };
  1962. tbb.init = function() {
  1963. vAPI.messaging.globalMessageManager.addMessageListener(
  1964. location.host + ':closePopup',
  1965. onPopupCloseRequested
  1966. );
  1967. var style = [
  1968. '#' + this.id + '.off {',
  1969. 'list-style-image: url(',
  1970. vAPI.getURL('img/browsericons/icon19-off.png'),
  1971. ');',
  1972. '}',
  1973. '#' + this.id + ' {',
  1974. 'list-style-image: url(',
  1975. vAPI.getURL('img/browsericons/icon19.png'),
  1976. ');',
  1977. '}',
  1978. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1979. 'width: 160px;',
  1980. 'height: 290px;',
  1981. 'overflow: hidden !important;',
  1982. '}',
  1983. '#' + this.id + '[badge]:not([badge=""])::after {',
  1984. 'position: absolute;',
  1985. 'margin-left: -16px;',
  1986. 'margin-top: 3px;',
  1987. 'padding: 1px 2px;',
  1988. 'font-size: 9px;',
  1989. 'font-weight: bold;',
  1990. 'color: #fff;',
  1991. 'background: #000;',
  1992. 'content: attr(badge);',
  1993. '}'
  1994. ];
  1995. styleURI = Services.io.newURI(
  1996. 'data:text/css,' + encodeURIComponent(style.join('')),
  1997. null,
  1998. null
  1999. );
  2000. this.closePopup = function(tabBrowser) {
  2001. CustomizableUI.hidePanelForNode(
  2002. tabBrowser.ownerDocument.getElementById(this.viewId)
  2003. );
  2004. };
  2005. CustomizableUI.createWidget(this);
  2006. cleanupTasks.push(shutdown);
  2007. };
  2008. })();
  2009. /******************************************************************************/
  2010. // Firefox Australis >= 36.
  2011. (function() {
  2012. var tbb = vAPI.toolbarButton;
  2013. if ( tbb.init !== null ) {
  2014. return;
  2015. }
  2016. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  2017. return null;
  2018. }
  2019. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2020. return null;
  2021. }
  2022. var CustomizableUI = null;
  2023. try {
  2024. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2025. } catch (ex) {
  2026. }
  2027. if ( CustomizableUI === null ) {
  2028. return null;
  2029. }
  2030. tbb.codePath = 'australis';
  2031. tbb.CustomizableUI = CustomizableUI;
  2032. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2033. var CUIEvents = {};
  2034. var badgeCSSRules = [
  2035. 'background: #000',
  2036. 'color: #fff'
  2037. ].join(';');
  2038. var updateBadgeStyle = function() {
  2039. for ( var win of vAPI.tabs.getWindows() ) {
  2040. var button = win.document.getElementById(tbb.id);
  2041. if ( button === null ) {
  2042. continue;
  2043. }
  2044. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2045. button,
  2046. 'class',
  2047. 'toolbarbutton-badge'
  2048. );
  2049. if ( !badge ) {
  2050. continue;
  2051. }
  2052. badge.style.cssText = badgeCSSRules;
  2053. }
  2054. };
  2055. var updateBadge = function() {
  2056. var wId = tbb.id;
  2057. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2058. for ( var win of vAPI.tabs.getWindows() ) {
  2059. var button = win.document.getElementById(wId);
  2060. if ( button === null ) {
  2061. continue;
  2062. }
  2063. if ( buttonInPanel ) {
  2064. button.classList.remove('badged-button');
  2065. continue;
  2066. }
  2067. button.classList.add('badged-button');
  2068. }
  2069. if ( buttonInPanel ) {
  2070. return;
  2071. }
  2072. // Anonymous elements need some time to be reachable
  2073. vAPI.setTimeout(updateBadgeStyle, 250);
  2074. }.bind(CUIEvents);
  2075. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2076. CUIEvents.onCustomizeEnd = updateBadge;
  2077. CUIEvents.onWidgetAdded = updateBadge;
  2078. CUIEvents.onWidgetUnderflow = updateBadge;
  2079. var onPopupCloseRequested = function({target}) {
  2080. if ( typeof tbb.closePopup === 'function' ) {
  2081. tbb.closePopup(target);
  2082. }
  2083. };
  2084. var shutdown = function() {
  2085. CustomizableUI.removeListener(CUIEvents);
  2086. CustomizableUI.destroyWidget(tbb.id);
  2087. for ( var win of vAPI.tabs.getWindows() ) {
  2088. var panel = win.document.getElementById(tbb.viewId);
  2089. panel.parentNode.removeChild(panel);
  2090. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2091. .getInterface(Ci.nsIDOMWindowUtils)
  2092. .removeSheet(styleURI, 1);
  2093. }
  2094. vAPI.messaging.globalMessageManager.removeMessageListener(
  2095. location.host + ':closePopup',
  2096. onPopupCloseRequested
  2097. );
  2098. };
  2099. var styleURI = null;
  2100. tbb.onBeforeCreated = function(doc) {
  2101. var panel = doc.createElement('panelview');
  2102. this.populatePanel(doc, panel);
  2103. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2104. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2105. .getInterface(Ci.nsIDOMWindowUtils)
  2106. .loadSheet(styleURI, 1);
  2107. };
  2108. tbb.onCreated = function(button) {
  2109. button.setAttribute('badge', '');
  2110. vAPI.setTimeout(updateBadge, 250);
  2111. };
  2112. tbb.onBeforePopupReady = function() {
  2113. // https://github.com/gorhill/uBlock/issues/83
  2114. // Add `portrait` class if width is constrained.
  2115. try {
  2116. this.contentDocument.body.classList.toggle(
  2117. 'portrait',
  2118. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2119. );
  2120. } catch (ex) {
  2121. /* noop */
  2122. }
  2123. };
  2124. tbb.closePopup = function(tabBrowser) {
  2125. CustomizableUI.hidePanelForNode(
  2126. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2127. );
  2128. };
  2129. tbb.init = function() {
  2130. vAPI.messaging.globalMessageManager.addMessageListener(
  2131. location.host + ':closePopup',
  2132. onPopupCloseRequested
  2133. );
  2134. CustomizableUI.addListener(CUIEvents);
  2135. var style = [
  2136. '#' + this.id + '.off {',
  2137. 'list-style-image: url(',
  2138. vAPI.getURL('img/browsericons/icon19-off.png'),
  2139. ');',
  2140. '}',
  2141. '#' + this.id + ' {',
  2142. 'list-style-image: url(',
  2143. vAPI.getURL('img/browsericons/icon19-19.png'),
  2144. ');',
  2145. '}',
  2146. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2147. 'width: 160px;',
  2148. 'height: 290px;',
  2149. 'overflow: hidden !important;',
  2150. '}'
  2151. ];
  2152. styleURI = Services.io.newURI(
  2153. 'data:text/css,' + encodeURIComponent(style.join('')),
  2154. null,
  2155. null
  2156. );
  2157. CustomizableUI.createWidget(this);
  2158. cleanupTasks.push(shutdown);
  2159. };
  2160. })();
  2161. /******************************************************************************/
  2162. // No toolbar button.
  2163. (function() {
  2164. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2165. // button code is one single cleanup task regardless of platform.
  2166. if ( vAPI.toolbarButton.init === null ) {
  2167. cleanupTasks.push(function(){});
  2168. }
  2169. })();
  2170. /******************************************************************************/
  2171. if ( vAPI.toolbarButton.init !== null ) {
  2172. vAPI.toolbarButton.init();
  2173. }
  2174. /******************************************************************************/
  2175. /******************************************************************************/
  2176. vAPI.contextMenu = {
  2177. contextMap: {
  2178. frame: 'inFrame',
  2179. link: 'onLink',
  2180. image: 'onImage',
  2181. audio: 'onAudio',
  2182. video: 'onVideo',
  2183. editable: 'onEditableArea'
  2184. }
  2185. };
  2186. /******************************************************************************/
  2187. vAPI.contextMenu.displayMenuItem = function({target}) {
  2188. var doc = target.ownerDocument;
  2189. var gContextMenu = doc.defaultView.gContextMenu;
  2190. if ( !gContextMenu.browser ) {
  2191. return;
  2192. }
  2193. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2194. var currentURI = gContextMenu.browser.currentURI;
  2195. // https://github.com/chrisaljoudi/uBlock/issues/105
  2196. // TODO: Should the element picker works on any kind of pages?
  2197. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2198. menuitem.hidden = true;
  2199. return;
  2200. }
  2201. var ctx = vAPI.contextMenu.contexts;
  2202. if ( !ctx ) {
  2203. menuitem.hidden = false;
  2204. return;
  2205. }
  2206. var ctxMap = vAPI.contextMenu.contextMap;
  2207. for ( var context of ctx ) {
  2208. if (
  2209. context === 'page' &&
  2210. !gContextMenu.onLink &&
  2211. !gContextMenu.onImage &&
  2212. !gContextMenu.onEditableArea &&
  2213. !gContextMenu.inFrame &&
  2214. !gContextMenu.onVideo &&
  2215. !gContextMenu.onAudio
  2216. ) {
  2217. menuitem.hidden = false;
  2218. return;
  2219. }
  2220. if ( gContextMenu[ctxMap[context]] ) {
  2221. menuitem.hidden = false;
  2222. return;
  2223. }
  2224. }
  2225. menuitem.hidden = true;
  2226. };
  2227. /******************************************************************************/
  2228. vAPI.contextMenu.register = function(doc) {
  2229. if ( !this.menuItemId ) {
  2230. return;
  2231. }
  2232. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2233. var menuitem = doc.createElement('menuitem');
  2234. menuitem.setAttribute('id', this.menuItemId);
  2235. menuitem.setAttribute('label', this.menuLabel);
  2236. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2237. menuitem.setAttribute('class', 'menuitem-iconic');
  2238. menuitem.addEventListener('command', this.onCommand);
  2239. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2240. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2241. };
  2242. /******************************************************************************/
  2243. vAPI.contextMenu.unregister = function(doc) {
  2244. if ( !this.menuItemId ) {
  2245. return;
  2246. }
  2247. var menuitem = doc.getElementById(this.menuItemId);
  2248. if ( menuitem === null ) {
  2249. return;
  2250. }
  2251. var contextMenu = menuitem.parentNode;
  2252. menuitem.removeEventListener('command', this.onCommand);
  2253. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2254. contextMenu.removeChild(menuitem);
  2255. };
  2256. /******************************************************************************/
  2257. vAPI.contextMenu.create = function(details, callback) {
  2258. this.menuItemId = details.id;
  2259. this.menuLabel = details.title;
  2260. this.contexts = details.contexts;
  2261. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2262. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2263. } else {
  2264. // default in Chrome
  2265. this.contexts = ['page'];
  2266. }
  2267. this.onCommand = function() {
  2268. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2269. var details = {
  2270. menuItemId: this.id
  2271. };
  2272. if ( gContextMenu.inFrame ) {
  2273. details.tagName = 'iframe';
  2274. // Probably won't work with e10s
  2275. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2276. } else if ( gContextMenu.onImage ) {
  2277. details.tagName = 'img';
  2278. details.srcUrl = gContextMenu.mediaURL;
  2279. } else if ( gContextMenu.onAudio ) {
  2280. details.tagName = 'audio';
  2281. details.srcUrl = gContextMenu.mediaURL;
  2282. } else if ( gContextMenu.onVideo ) {
  2283. details.tagName = 'video';
  2284. details.srcUrl = gContextMenu.mediaURL;
  2285. } else if ( gContextMenu.onLink ) {
  2286. details.tagName = 'a';
  2287. details.linkUrl = gContextMenu.linkURL;
  2288. }
  2289. callback(details, {
  2290. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2291. url: gContextMenu.browser.currentURI.asciiSpec
  2292. });
  2293. };
  2294. for ( var win of vAPI.tabs.getWindows() ) {
  2295. this.register(win.document);
  2296. }
  2297. };
  2298. /******************************************************************************/
  2299. vAPI.contextMenu.remove = function() {
  2300. for ( var win of vAPI.tabs.getWindows() ) {
  2301. this.unregister(win.document);
  2302. }
  2303. this.menuItemId = null;
  2304. this.menuLabel = null;
  2305. this.contexts = null;
  2306. this.onCommand = null;
  2307. };
  2308. /******************************************************************************/
  2309. /******************************************************************************/
  2310. var optionsObserver = {
  2311. addonId: 'uMatrix@raymondhill.net',
  2312. register: function() {
  2313. Services.obs.addObserver(this, 'addon-options-displayed', false);
  2314. cleanupTasks.push(this.unregister.bind(this));
  2315. var browser = tabWatcher.currentBrowser();
  2316. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  2317. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  2318. }
  2319. },
  2320. unregister: function() {
  2321. Services.obs.removeObserver(this, 'addon-options-displayed');
  2322. },
  2323. setupOptionsButton: function(doc, id, page) {
  2324. var button = doc.getElementById(id);
  2325. if ( button === null ) {
  2326. return;
  2327. }
  2328. button.addEventListener('command', function() {
  2329. vAPI.tabs.open({ url: page, index: -1 });
  2330. });
  2331. button.label = vAPI.i18n(id);
  2332. },
  2333. observe: function(doc, topic, addonId) {
  2334. if ( addonId !== this.addonId ) {
  2335. return;
  2336. }
  2337. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  2338. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  2339. }
  2340. };
  2341. optionsObserver.register();
  2342. /******************************************************************************/
  2343. /******************************************************************************/
  2344. vAPI.lastError = function() {
  2345. return null;
  2346. };
  2347. /******************************************************************************/
  2348. /******************************************************************************/
  2349. // This is called only once, when everything has been loaded in memory after
  2350. // the extension was launched. It can be used to inject content scripts
  2351. // in already opened web pages, to remove whatever nuisance could make it to
  2352. // the web pages before uBlock was ready.
  2353. vAPI.onLoadAllCompleted = function() {
  2354. for ( var browser of tabWatcher.browsers() ) {
  2355. browser.messageManager.sendAsyncMessage(
  2356. location.host + '-load-completed'
  2357. );
  2358. }
  2359. };
  2360. /******************************************************************************/
  2361. /******************************************************************************/
  2362. // Likelihood is that we do not have to punycode: given punycode overhead,
  2363. // it's faster to check and skip than do it unconditionally all the time.
  2364. var punycodeHostname = punycode.toASCII;
  2365. var isNotASCII = /[^\x21-\x7F]/;
  2366. vAPI.punycodeHostname = function(hostname) {
  2367. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2368. };
  2369. vAPI.punycodeURL = function(url) {
  2370. if ( isNotASCII.test(url) ) {
  2371. return Services.io.newURI(url, null, null).asciiSpec;
  2372. }
  2373. return url;
  2374. };
  2375. /******************************************************************************/
  2376. /******************************************************************************/
  2377. vAPI.browserData = {};
  2378. /******************************************************************************/
  2379. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2380. vAPI.browserData.clearCache = function(callback) {
  2381. // PURGE_DISK_DATA_ONLY:1
  2382. // PURGE_DISK_ALL:2
  2383. // PURGE_EVERYTHING:3
  2384. // However I verified that not argument does clear the cache data.
  2385. Services.cache2.clear();
  2386. if ( typeof callback === 'function' ) {
  2387. callback();
  2388. }
  2389. };
  2390. /******************************************************************************/
  2391. vAPI.browserData.clearOrigin = function(/* domain */) {
  2392. // TODO
  2393. };
  2394. /******************************************************************************/
  2395. /******************************************************************************/
  2396. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2397. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2398. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2399. vAPI.cookies = {};
  2400. /******************************************************************************/
  2401. vAPI.cookies.CookieEntry = function(ffCookie) {
  2402. this.domain = ffCookie.host;
  2403. this.name = ffCookie.name;
  2404. this.path = ffCookie.path;
  2405. this.secure = ffCookie.isSecure === true;
  2406. this.session = ffCookie.expires === 0;
  2407. this.value = ffCookie.value;
  2408. };
  2409. /******************************************************************************/
  2410. vAPI.cookies.start = function() {
  2411. Services.obs.addObserver(this, 'cookie-changed', false);
  2412. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2413. cleanupTasks.push(this.stop.bind(this));
  2414. };
  2415. /******************************************************************************/
  2416. vAPI.cookies.stop = function() {
  2417. Services.obs.removeObserver(this, 'cookie-changed');
  2418. Services.obs.removeObserver(this, 'private-cookie-changed');
  2419. };
  2420. /******************************************************************************/
  2421. vAPI.cookies.observe = function(subject, topic, reason) {
  2422. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2423. // return;
  2424. //}
  2425. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  2426. return;
  2427. }
  2428. if ( typeof this.onChanged === 'function' ) {
  2429. this.onChanged(new this.CookieEntry(subject));
  2430. }
  2431. };
  2432. /******************************************************************************/
  2433. // Meant and expected to be asynchronous.
  2434. vAPI.cookies.getAll = function(callback) {
  2435. if ( typeof callback !== 'function' ) {
  2436. return;
  2437. }
  2438. var onAsync = function() {
  2439. var out = [];
  2440. var enumerator = Services.cookies.enumerator;
  2441. var ffcookie;
  2442. while ( enumerator.hasMoreElements() ) {
  2443. ffcookie = enumerator.getNext();
  2444. if ( ffcookie instanceof Ci.nsICookie ) {
  2445. out.push(new this.CookieEntry(ffcookie));
  2446. }
  2447. }
  2448. callback(out);
  2449. };
  2450. vAPI.setTimeout(onAsync.bind(this), 0);
  2451. };
  2452. /******************************************************************************/
  2453. vAPI.cookies.remove = function(details, callback) {
  2454. var uri = Services.io.newURI(details.url, null, null);
  2455. var cookies = Services.cookies;
  2456. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  2457. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  2458. if ( typeof callback === 'function' ) {
  2459. callback({
  2460. domain: uri.asciiHost,
  2461. name: details.name,
  2462. path: uri.path
  2463. });
  2464. }
  2465. };
  2466. /******************************************************************************/
  2467. /******************************************************************************/
  2468. })();
  2469. /******************************************************************************/