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.

3085 lines
95 KiB

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