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.

3346 lines
104 KiB

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