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.

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