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.

3349 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. // https://github.com/gorhill/uBlock/issues/763
  2049. // We are done if our toolbar button is already installed in one of the
  2050. // toolbar.
  2051. if ( palette !== null && toolbarButton.parentElement !== palette ) {
  2052. return;
  2053. }
  2054. // No button yet so give it a default location. If forcing the button,
  2055. // just put in in the palette rather than on any specific toolbar (who
  2056. // knows what toolbars will be available or visible!)
  2057. if ( navbar !== null && !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  2058. // https://github.com/gorhill/uBlock/issues/264
  2059. // Find a child customizable palette, if any.
  2060. navbar = navbar.querySelector('.customization-target') || navbar;
  2061. navbar.appendChild(toolbarButton);
  2062. navbar.setAttribute('currentset', navbar.currentSet);
  2063. document.persist(navbar.id, 'currentset');
  2064. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  2065. }
  2066. };
  2067. var onPopupCloseRequested = function({target}) {
  2068. if ( typeof tbb.closePopup === 'function' ) {
  2069. tbb.closePopup(target);
  2070. }
  2071. };
  2072. var shutdown = function() {
  2073. for ( var win of winWatcher.getWindows() ) {
  2074. var toolbarButton = win.document.getElementById(tbb.id);
  2075. if ( toolbarButton ) {
  2076. toolbarButton.parentNode.removeChild(toolbarButton);
  2077. }
  2078. }
  2079. if ( sss === null ) {
  2080. return;
  2081. }
  2082. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2083. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2084. }
  2085. sss = null;
  2086. styleSheetUri = null;
  2087. vAPI.messaging.globalMessageManager.removeMessageListener(
  2088. location.host + ':closePopup',
  2089. onPopupCloseRequested
  2090. );
  2091. };
  2092. tbb.attachToNewWindow = function(win) {
  2093. addLegacyToolbarButton(win);
  2094. };
  2095. tbb.init = function() {
  2096. vAPI.messaging.globalMessageManager.addMessageListener(
  2097. location.host + ':closePopup',
  2098. onPopupCloseRequested
  2099. );
  2100. sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
  2101. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  2102. // Register global so it works in all windows, including palette
  2103. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  2104. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  2105. }
  2106. cleanupTasks.push(shutdown);
  2107. };
  2108. })();
  2109. /******************************************************************************/
  2110. // Firefox Australis < 36.
  2111. (function() {
  2112. var tbb = vAPI.toolbarButton;
  2113. if ( tbb.init !== null ) {
  2114. return;
  2115. }
  2116. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  2117. return null;
  2118. }
  2119. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2120. return null;
  2121. }
  2122. var CustomizableUI = null;
  2123. try {
  2124. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2125. } catch (ex) {
  2126. }
  2127. if ( CustomizableUI === null ) {
  2128. return;
  2129. }
  2130. tbb.codePath = 'australis';
  2131. tbb.CustomizableUI = CustomizableUI;
  2132. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2133. var styleURI = null;
  2134. var onPopupCloseRequested = function({target}) {
  2135. if ( typeof tbb.closePopup === 'function' ) {
  2136. tbb.closePopup(target);
  2137. }
  2138. };
  2139. var shutdown = function() {
  2140. CustomizableUI.destroyWidget(tbb.id);
  2141. for ( var win of winWatcher.getWindows() ) {
  2142. var panel = win.document.getElementById(tbb.viewId);
  2143. panel.parentNode.removeChild(panel);
  2144. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2145. .getInterface(Ci.nsIDOMWindowUtils)
  2146. .removeSheet(styleURI, 1);
  2147. }
  2148. vAPI.messaging.globalMessageManager.removeMessageListener(
  2149. location.host + ':closePopup',
  2150. onPopupCloseRequested
  2151. );
  2152. };
  2153. tbb.onBeforeCreated = function(doc) {
  2154. var panel = doc.createElement('panelview');
  2155. this.populatePanel(doc, panel);
  2156. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2157. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2158. .getInterface(Ci.nsIDOMWindowUtils)
  2159. .loadSheet(styleURI, 1);
  2160. };
  2161. tbb.onBeforePopupReady = function() {
  2162. // https://github.com/gorhill/uBlock/issues/83
  2163. // Add `portrait` class if width is constrained.
  2164. try {
  2165. this.contentDocument.body.classList.toggle(
  2166. 'portrait',
  2167. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2168. );
  2169. } catch (ex) {
  2170. /* noop */
  2171. }
  2172. };
  2173. tbb.init = function() {
  2174. vAPI.messaging.globalMessageManager.addMessageListener(
  2175. location.host + ':closePopup',
  2176. onPopupCloseRequested
  2177. );
  2178. var style = [
  2179. '#' + this.id + '.off {',
  2180. 'list-style-image: url(',
  2181. vAPI.getURL('img/browsericons/icon19-off.png'),
  2182. ');',
  2183. '}',
  2184. '#' + this.id + ' {',
  2185. 'list-style-image: url(',
  2186. vAPI.getURL('img/browsericons/icon19.png'),
  2187. ');',
  2188. '}',
  2189. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2190. 'width: 160px;',
  2191. 'height: 290px;',
  2192. 'overflow: hidden !important;',
  2193. '}',
  2194. '#' + this.id + '[badge]:not([badge=""])::after {',
  2195. 'position: absolute;',
  2196. 'margin-left: -16px;',
  2197. 'margin-top: 3px;',
  2198. 'padding: 1px 2px;',
  2199. 'font-size: 9px;',
  2200. 'font-weight: bold;',
  2201. 'color: #fff;',
  2202. 'background: #000;',
  2203. 'content: attr(badge);',
  2204. '}'
  2205. ];
  2206. styleURI = Services.io.newURI(
  2207. 'data:text/css,' + encodeURIComponent(style.join('')),
  2208. null,
  2209. null
  2210. );
  2211. this.closePopup = function(tabBrowser) {
  2212. CustomizableUI.hidePanelForNode(
  2213. tabBrowser.ownerDocument.getElementById(this.viewId)
  2214. );
  2215. };
  2216. CustomizableUI.createWidget(this);
  2217. cleanupTasks.push(shutdown);
  2218. };
  2219. })();
  2220. /******************************************************************************/
  2221. // Firefox Australis >= 36.
  2222. (function() {
  2223. var tbb = vAPI.toolbarButton;
  2224. if ( tbb.init !== null ) {
  2225. return;
  2226. }
  2227. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  2228. return null;
  2229. }
  2230. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  2231. return null;
  2232. }
  2233. var CustomizableUI = null;
  2234. try {
  2235. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  2236. } catch (ex) {
  2237. }
  2238. if ( CustomizableUI === null ) {
  2239. return null;
  2240. }
  2241. tbb.codePath = 'australis';
  2242. tbb.CustomizableUI = CustomizableUI;
  2243. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  2244. var CUIEvents = {};
  2245. var badgeCSSRules = [
  2246. 'background: #000',
  2247. 'color: #fff'
  2248. ].join(';');
  2249. var updateBadgeStyle = function() {
  2250. for ( var win of winWatcher.getWindows() ) {
  2251. var button = win.document.getElementById(tbb.id);
  2252. if ( button === null ) {
  2253. continue;
  2254. }
  2255. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2256. button,
  2257. 'class',
  2258. 'toolbarbutton-badge'
  2259. );
  2260. if ( !badge ) {
  2261. continue;
  2262. }
  2263. badge.style.cssText = badgeCSSRules;
  2264. }
  2265. };
  2266. var updateBadge = function() {
  2267. var wId = tbb.id;
  2268. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2269. for ( var win of winWatcher.getWindows() ) {
  2270. var button = win.document.getElementById(wId);
  2271. if ( button === null ) {
  2272. continue;
  2273. }
  2274. if ( buttonInPanel ) {
  2275. button.classList.remove('badged-button');
  2276. continue;
  2277. }
  2278. button.classList.add('badged-button');
  2279. }
  2280. if ( buttonInPanel ) {
  2281. return;
  2282. }
  2283. // Anonymous elements need some time to be reachable
  2284. vAPI.setTimeout(updateBadgeStyle, 250);
  2285. }.bind(CUIEvents);
  2286. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2287. CUIEvents.onCustomizeEnd = updateBadge;
  2288. CUIEvents.onWidgetAdded = updateBadge;
  2289. CUIEvents.onWidgetUnderflow = updateBadge;
  2290. var onPopupCloseRequested = function({target}) {
  2291. if ( typeof tbb.closePopup === 'function' ) {
  2292. tbb.closePopup(target);
  2293. }
  2294. };
  2295. var shutdown = function() {
  2296. for ( var win of winWatcher.getWindows() ) {
  2297. var panel = win.document.getElementById(tbb.viewId);
  2298. if ( panel !== null && panel.parentNode !== null ) {
  2299. panel.parentNode.removeChild(panel);
  2300. }
  2301. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2302. .getInterface(Ci.nsIDOMWindowUtils)
  2303. .removeSheet(styleURI, 1);
  2304. }
  2305. CustomizableUI.removeListener(CUIEvents);
  2306. CustomizableUI.destroyWidget(tbb.id);
  2307. vAPI.messaging.globalMessageManager.removeMessageListener(
  2308. location.host + ':closePopup',
  2309. onPopupCloseRequested
  2310. );
  2311. };
  2312. var styleURI = null;
  2313. tbb.onBeforeCreated = function(doc) {
  2314. var panel = doc.createElement('panelview');
  2315. this.populatePanel(doc, panel);
  2316. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2317. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2318. .getInterface(Ci.nsIDOMWindowUtils)
  2319. .loadSheet(styleURI, 1);
  2320. };
  2321. tbb.onCreated = function(button) {
  2322. button.setAttribute('badge', '');
  2323. vAPI.setTimeout(updateBadge, 250);
  2324. };
  2325. tbb.onBeforePopupReady = function() {
  2326. // https://github.com/gorhill/uBlock/issues/83
  2327. // Add `portrait` class if width is constrained.
  2328. try {
  2329. this.contentDocument.body.classList.toggle(
  2330. 'portrait',
  2331. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2332. );
  2333. } catch (ex) {
  2334. /* noop */
  2335. }
  2336. };
  2337. tbb.closePopup = function(tabBrowser) {
  2338. CustomizableUI.hidePanelForNode(
  2339. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2340. );
  2341. };
  2342. tbb.init = function() {
  2343. vAPI.messaging.globalMessageManager.addMessageListener(
  2344. location.host + ':closePopup',
  2345. onPopupCloseRequested
  2346. );
  2347. CustomizableUI.addListener(CUIEvents);
  2348. var style = [
  2349. '#' + this.id + '.off {',
  2350. 'list-style-image: url(',
  2351. vAPI.getURL('img/browsericons/icon19-off.png'),
  2352. ');',
  2353. '}',
  2354. '#' + this.id + ' {',
  2355. 'list-style-image: url(',
  2356. vAPI.getURL('img/browsericons/icon19-19.png'),
  2357. ');',
  2358. '}',
  2359. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2360. 'width: 160px;',
  2361. 'height: 290px;',
  2362. 'overflow: hidden !important;',
  2363. '}'
  2364. ];
  2365. styleURI = Services.io.newURI(
  2366. 'data:text/css,' + encodeURIComponent(style.join('')),
  2367. null,
  2368. null
  2369. );
  2370. CustomizableUI.createWidget(this);
  2371. cleanupTasks.push(shutdown);
  2372. };
  2373. })();
  2374. /******************************************************************************/
  2375. // No toolbar button.
  2376. (function() {
  2377. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2378. // button code is one single cleanup task regardless of platform.
  2379. if ( vAPI.toolbarButton.init === null ) {
  2380. cleanupTasks.push(function(){});
  2381. }
  2382. })();
  2383. /******************************************************************************/
  2384. if ( vAPI.toolbarButton.init !== null ) {
  2385. vAPI.toolbarButton.init();
  2386. }
  2387. /******************************************************************************/
  2388. /******************************************************************************/
  2389. vAPI.contextMenu = {
  2390. contextMap: {
  2391. frame: 'inFrame',
  2392. link: 'onLink',
  2393. image: 'onImage',
  2394. audio: 'onAudio',
  2395. video: 'onVideo',
  2396. editable: 'onEditableArea'
  2397. }
  2398. };
  2399. /******************************************************************************/
  2400. vAPI.contextMenu.displayMenuItem = function({target}) {
  2401. var doc = target.ownerDocument;
  2402. var gContextMenu = doc.defaultView.gContextMenu;
  2403. if ( !gContextMenu.browser ) {
  2404. return;
  2405. }
  2406. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2407. var currentURI = gContextMenu.browser.currentURI;
  2408. // https://github.com/chrisaljoudi/uBlock/issues/105
  2409. // TODO: Should the element picker works on any kind of pages?
  2410. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2411. menuitem.setAttribute('hidden', true);
  2412. return;
  2413. }
  2414. var ctx = vAPI.contextMenu.contexts;
  2415. if ( !ctx ) {
  2416. menuitem.setAttribute('hidden', false);
  2417. return;
  2418. }
  2419. var ctxMap = vAPI.contextMenu.contextMap;
  2420. for ( var context of ctx ) {
  2421. if (
  2422. context === 'page' &&
  2423. !gContextMenu.onLink &&
  2424. !gContextMenu.onImage &&
  2425. !gContextMenu.onEditableArea &&
  2426. !gContextMenu.inFrame &&
  2427. !gContextMenu.onVideo &&
  2428. !gContextMenu.onAudio
  2429. ) {
  2430. menuitem.setAttribute('hidden', false);
  2431. return;
  2432. }
  2433. if (
  2434. ctxMap.hasOwnProperty(context) &&
  2435. gContextMenu[ctxMap[context]]
  2436. ) {
  2437. menuitem.setAttribute('hidden', false);
  2438. return;
  2439. }
  2440. }
  2441. menuitem.setAttribute('hidden', true);
  2442. };
  2443. /******************************************************************************/
  2444. vAPI.contextMenu.register = (function() {
  2445. var register = function(doc) {
  2446. if ( !this.menuItemId ) {
  2447. return;
  2448. }
  2449. // Already installed?
  2450. if ( doc.getElementById(this.menuItemId) !== null ) {
  2451. return;
  2452. }
  2453. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2454. var menuitem = doc.createElement('menuitem');
  2455. menuitem.setAttribute('id', this.menuItemId);
  2456. menuitem.setAttribute('label', this.menuLabel);
  2457. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2458. menuitem.setAttribute('class', 'menuitem-iconic');
  2459. menuitem.addEventListener('command', this.onCommand);
  2460. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2461. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2462. };
  2463. // https://github.com/gorhill/uBlock/issues/906
  2464. // Be sure document.readyState is 'complete': it could happen at launch
  2465. // time that we are called by vAPI.contextMenu.create() directly before
  2466. // the environment is properly initialized.
  2467. var registerSafely = function(doc, tryCount) {
  2468. if ( doc.readyState === 'complete' ) {
  2469. register.call(this, doc);
  2470. return;
  2471. }
  2472. if ( typeof tryCount !== 'number' ) {
  2473. tryCount = 0;
  2474. }
  2475. tryCount += 1;
  2476. if ( tryCount < 8 ) {
  2477. vAPI.setTimeout(registerSafely.bind(this, doc, tryCount), 200);
  2478. }
  2479. };
  2480. return registerSafely;
  2481. })();
  2482. /******************************************************************************/
  2483. vAPI.contextMenu.unregister = function(doc) {
  2484. if ( !this.menuItemId ) {
  2485. return;
  2486. }
  2487. var menuitem = doc.getElementById(this.menuItemId);
  2488. if ( menuitem === null ) {
  2489. return;
  2490. }
  2491. var contextMenu = menuitem.parentNode;
  2492. menuitem.removeEventListener('command', this.onCommand);
  2493. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2494. contextMenu.removeChild(menuitem);
  2495. };
  2496. /******************************************************************************/
  2497. vAPI.contextMenu.create = function(details, callback) {
  2498. this.menuItemId = details.id;
  2499. this.menuLabel = details.title;
  2500. this.contexts = details.contexts;
  2501. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2502. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2503. } else {
  2504. // default in Chrome
  2505. this.contexts = ['page'];
  2506. }
  2507. this.onCommand = function() {
  2508. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2509. var details = {
  2510. menuItemId: this.id
  2511. };
  2512. if ( gContextMenu.inFrame ) {
  2513. details.tagName = 'iframe';
  2514. // Probably won't work with e10s
  2515. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2516. } else if ( gContextMenu.onImage ) {
  2517. details.tagName = 'img';
  2518. details.srcUrl = gContextMenu.mediaURL;
  2519. } else if ( gContextMenu.onAudio ) {
  2520. details.tagName = 'audio';
  2521. details.srcUrl = gContextMenu.mediaURL;
  2522. } else if ( gContextMenu.onVideo ) {
  2523. details.tagName = 'video';
  2524. details.srcUrl = gContextMenu.mediaURL;
  2525. } else if ( gContextMenu.onLink ) {
  2526. details.tagName = 'a';
  2527. details.linkUrl = gContextMenu.linkURL;
  2528. }
  2529. callback(details, {
  2530. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2531. url: gContextMenu.browser.currentURI.asciiSpec
  2532. });
  2533. };
  2534. for ( var win of winWatcher.getWindows() ) {
  2535. this.register(win.document);
  2536. }
  2537. };
  2538. /******************************************************************************/
  2539. vAPI.contextMenu.remove = function() {
  2540. for ( var win of winWatcher.getWindows() ) {
  2541. this.unregister(win.document);
  2542. }
  2543. this.menuItemId = null;
  2544. this.menuLabel = null;
  2545. this.contexts = null;
  2546. this.onCommand = null;
  2547. };
  2548. /******************************************************************************/
  2549. /******************************************************************************/
  2550. var optionsObserver = {
  2551. addonId: 'uMatrix@raymondhill.net',
  2552. register: function() {
  2553. Services.obs.addObserver(this, 'addon-options-displayed', false);
  2554. cleanupTasks.push(this.unregister.bind(this));
  2555. var browser = tabWatcher.currentBrowser();
  2556. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  2557. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  2558. }
  2559. },
  2560. unregister: function() {
  2561. Services.obs.removeObserver(this, 'addon-options-displayed');
  2562. },
  2563. setupOptionsButton: function(doc, id, page) {
  2564. var button = doc.getElementById(id);
  2565. if ( button === null ) {
  2566. return;
  2567. }
  2568. button.addEventListener('command', function() {
  2569. vAPI.tabs.open({ url: page, index: -1 });
  2570. });
  2571. button.label = vAPI.i18n(id);
  2572. },
  2573. observe: function(doc, topic, addonId) {
  2574. if ( addonId !== this.addonId ) {
  2575. return;
  2576. }
  2577. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  2578. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  2579. }
  2580. };
  2581. optionsObserver.register();
  2582. /******************************************************************************/
  2583. /******************************************************************************/
  2584. vAPI.lastError = function() {
  2585. return null;
  2586. };
  2587. /******************************************************************************/
  2588. /******************************************************************************/
  2589. // This is called only once, when everything has been loaded in memory after
  2590. // the extension was launched. It can be used to inject content scripts
  2591. // in already opened web pages, to remove whatever nuisance could make it to
  2592. // the web pages before uBlock was ready.
  2593. vAPI.onLoadAllCompleted = function() {
  2594. for ( var browser of tabWatcher.browsers() ) {
  2595. browser.messageManager.sendAsyncMessage(
  2596. location.host + '-load-completed'
  2597. );
  2598. }
  2599. };
  2600. /******************************************************************************/
  2601. /******************************************************************************/
  2602. // Likelihood is that we do not have to punycode: given punycode overhead,
  2603. // it's faster to check and skip than do it unconditionally all the time.
  2604. var punycodeHostname = punycode.toASCII;
  2605. var isNotASCII = /[^\x21-\x7F]/;
  2606. vAPI.punycodeHostname = function(hostname) {
  2607. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2608. };
  2609. vAPI.punycodeURL = function(url) {
  2610. if ( isNotASCII.test(url) ) {
  2611. return Services.io.newURI(url, null, null).asciiSpec;
  2612. }
  2613. return url;
  2614. };
  2615. /******************************************************************************/
  2616. /******************************************************************************/
  2617. vAPI.cloud = (function() {
  2618. var extensionBranchPath = 'extensions.' + location.host;
  2619. var cloudBranchPath = extensionBranchPath + '.cloudStorage';
  2620. // https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658
  2621. // We must use get/setComplexValue in order to properly handle strings
  2622. // with unicode characters.
  2623. var iss = Ci.nsISupportsString;
  2624. var argstr = Components.classes['@mozilla.org/supports-string;1']
  2625. .createInstance(iss);
  2626. var options = {
  2627. defaultDeviceName: '',
  2628. deviceName: ''
  2629. };
  2630. // User-supplied device name.
  2631. try {
  2632. options.deviceName = Services.prefs
  2633. .getBranch(extensionBranchPath + '.')
  2634. .getComplexValue('deviceName', iss)
  2635. .data;
  2636. } catch(ex) {
  2637. }
  2638. var getDefaultDeviceName = function() {
  2639. var name = '';
  2640. try {
  2641. name = Services.prefs
  2642. .getBranch('services.sync.client.')
  2643. .getComplexValue('name', iss)
  2644. .data;
  2645. } catch(ex) {
  2646. }
  2647. return name || window.navigator.platform || window.navigator.oscpu;
  2648. };
  2649. var start = function(dataKeys) {
  2650. var extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.');
  2651. var syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.');
  2652. // Mark config entries as syncable
  2653. argstr.data = '';
  2654. var dataKey;
  2655. for ( var i = 0; i < dataKeys.length; i++ ) {
  2656. dataKey = dataKeys[i];
  2657. if ( extensionBranch.prefHasUserValue('cloudStorage.' + dataKey) === false ) {
  2658. extensionBranch.setComplexValue('cloudStorage.' + dataKey, iss, argstr);
  2659. }
  2660. syncBranch.setBoolPref(cloudBranchPath + '.' + dataKey, true);
  2661. }
  2662. };
  2663. var push = function(datakey, data, callback) {
  2664. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2665. var bin = {
  2666. 'source': options.deviceName || getDefaultDeviceName(),
  2667. 'tstamp': Date.now(),
  2668. 'data': data,
  2669. 'size': 0
  2670. };
  2671. bin.size = JSON.stringify(bin).length;
  2672. argstr.data = JSON.stringify(bin);
  2673. branch.setComplexValue(datakey, iss, argstr);
  2674. if ( typeof callback === 'function' ) {
  2675. callback();
  2676. }
  2677. };
  2678. var pull = function(datakey, callback) {
  2679. var result = null;
  2680. var branch = Services.prefs.getBranch(cloudBranchPath + '.');
  2681. try {
  2682. var json = branch.getComplexValue(datakey, iss).data;
  2683. if ( typeof json === 'string' ) {
  2684. result = JSON.parse(json);
  2685. }
  2686. } catch(ex) {
  2687. }
  2688. callback(result);
  2689. };
  2690. var getOptions = function(callback) {
  2691. if ( typeof callback !== 'function' ) {
  2692. return;
  2693. }
  2694. options.defaultDeviceName = getDefaultDeviceName();
  2695. callback(options);
  2696. };
  2697. var setOptions = function(details, callback) {
  2698. if ( typeof details !== 'object' || details === null ) {
  2699. return;
  2700. }
  2701. var branch = Services.prefs.getBranch(extensionBranchPath + '.');
  2702. if ( typeof details.deviceName === 'string' ) {
  2703. argstr.data = details.deviceName;
  2704. branch.setComplexValue('deviceName', iss, argstr);
  2705. options.deviceName = details.deviceName;
  2706. }
  2707. getOptions(callback);
  2708. };
  2709. return {
  2710. start: start,
  2711. push: push,
  2712. pull: pull,
  2713. getOptions: getOptions,
  2714. setOptions: setOptions
  2715. };
  2716. })();
  2717. /******************************************************************************/
  2718. /******************************************************************************/
  2719. vAPI.browserData = {};
  2720. /******************************************************************************/
  2721. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2722. vAPI.browserData.clearCache = function(callback) {
  2723. // PURGE_DISK_DATA_ONLY:1
  2724. // PURGE_DISK_ALL:2
  2725. // PURGE_EVERYTHING:3
  2726. // However I verified that no argument does clear the cache data.
  2727. // There is no cache2 for older versions of Firefox.
  2728. if ( Services.cache2 ) {
  2729. Services.cache2.clear();
  2730. } else if ( Services.cache ) {
  2731. Services.cache.evictEntries(Services.cache.STORE_ON_DISK);
  2732. }
  2733. if ( typeof callback === 'function' ) {
  2734. callback();
  2735. }
  2736. };
  2737. /******************************************************************************/
  2738. vAPI.browserData.clearOrigin = function(/* domain */) {
  2739. // TODO
  2740. };
  2741. /******************************************************************************/
  2742. /******************************************************************************/
  2743. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2744. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2745. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2746. vAPI.cookies = {};
  2747. /******************************************************************************/
  2748. vAPI.cookies.CookieEntry = function(ffCookie) {
  2749. this.domain = ffCookie.host;
  2750. this.name = ffCookie.name;
  2751. this.path = ffCookie.path;
  2752. this.secure = ffCookie.isSecure === true;
  2753. this.session = ffCookie.expires === 0;
  2754. this.value = ffCookie.value;
  2755. };
  2756. /******************************************************************************/
  2757. vAPI.cookies.start = function() {
  2758. Services.obs.addObserver(this, 'cookie-changed', false);
  2759. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2760. cleanupTasks.push(this.stop.bind(this));
  2761. };
  2762. /******************************************************************************/
  2763. vAPI.cookies.stop = function() {
  2764. Services.obs.removeObserver(this, 'cookie-changed');
  2765. Services.obs.removeObserver(this, 'private-cookie-changed');
  2766. };
  2767. /******************************************************************************/
  2768. vAPI.cookies.observe = function(subject, topic, reason) {
  2769. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2770. // return;
  2771. //}
  2772. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  2773. return;
  2774. }
  2775. if ( typeof this.onChanged === 'function' ) {
  2776. this.onChanged(new this.CookieEntry(subject));
  2777. }
  2778. };
  2779. /******************************************************************************/
  2780. // Meant and expected to be asynchronous.
  2781. vAPI.cookies.getAll = function(callback) {
  2782. if ( typeof callback !== 'function' ) {
  2783. return;
  2784. }
  2785. var onAsync = function() {
  2786. var out = [];
  2787. var enumerator = Services.cookies.enumerator;
  2788. var ffcookie;
  2789. while ( enumerator.hasMoreElements() ) {
  2790. ffcookie = enumerator.getNext();
  2791. if ( ffcookie instanceof Ci.nsICookie ) {
  2792. out.push(new this.CookieEntry(ffcookie));
  2793. }
  2794. }
  2795. callback(out);
  2796. };
  2797. vAPI.setTimeout(onAsync.bind(this), 0);
  2798. };
  2799. /******************************************************************************/
  2800. vAPI.cookies.remove = function(details, callback) {
  2801. var uri = Services.io.newURI(details.url, null, null);
  2802. var cookies = Services.cookies;
  2803. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  2804. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  2805. if ( typeof callback === 'function' ) {
  2806. callback({
  2807. domain: uri.asciiHost,
  2808. name: details.name,
  2809. path: uri.path
  2810. });
  2811. }
  2812. };
  2813. /******************************************************************************/
  2814. /******************************************************************************/
  2815. })();
  2816. /******************************************************************************/