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.

3368 lines
105 KiB

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