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.

2934 lines
90 KiB

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