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.

2124 lines
63 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. µBlock - a browser extension to block requests.
  3. Copyright (C) 2014 The µBlock authors
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see {http://www.gnu.org/licenses/}.
  14. Home: https://github.com/gorhill/uMatrix
  15. */
  16. /* jshint bitwise: false, boss: true, esnext: true */
  17. /* global self, Components, punycode, µBlock */
  18. // For background page
  19. /******************************************************************************/
  20. (function() {
  21. 'use strict';
  22. /******************************************************************************/
  23. // Useful links
  24. //
  25. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface
  26. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm
  27. /******************************************************************************/
  28. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  29. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  30. /******************************************************************************/
  31. var vAPI = self.vAPI = self.vAPI || {};
  32. vAPI.firefox = true;
  33. /******************************************************************************/
  34. vAPI.app = {
  35. name: 'uMatrix',
  36. version: location.hash.slice(1)
  37. };
  38. /******************************************************************************/
  39. vAPI.app.start = function() {
  40. };
  41. /******************************************************************************/
  42. vAPI.app.stop = function() {
  43. };
  44. /******************************************************************************/
  45. vAPI.app.restart = function() {
  46. // Listening in bootstrap.js
  47. Cc['@mozilla.org/childprocessmessagemanager;1']
  48. .getService(Ci.nsIMessageSender)
  49. .sendAsyncMessage(location.host + '-restart');
  50. };
  51. /******************************************************************************/
  52. // https://stackoverflow.com/questions/6715571/how-to-get-result-of-console-trace-as-string-in-javascript-with-chrome-or-fire/28118170#28118170
  53. /*
  54. function logStackTrace(msg) {
  55. var stack;
  56. try {
  57. throw new Error('');
  58. }
  59. catch (error) {
  60. stack = error.stack || '';
  61. }
  62. stack = stack.split('\n').map(function(line) { return line.trim(); });
  63. stack.shift();
  64. if ( msg ) {
  65. stack.unshift(msg);
  66. }
  67. console.log(stack.join('\n'));
  68. }
  69. */
  70. /******************************************************************************/
  71. // List of things that needs to be destroyed when disabling the extension
  72. // Only functions should be added to it
  73. var cleanupTasks = [];
  74. // This must be updated manually, every time a new task is added/removed
  75. // Fixed by github.com/AlexVallat:
  76. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  77. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  78. var expectedNumberOfCleanups = 7;
  79. window.addEventListener('unload', function() {
  80. for ( var cleanup of cleanupTasks ) {
  81. cleanup();
  82. }
  83. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  84. console.error(
  85. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  86. cleanupTasks.length,
  87. expectedNumberOfCleanups
  88. );
  89. }
  90. // frameModule needs to be cleared too
  91. var frameModule = {};
  92. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  93. frameModule.contentObserver.unregister();
  94. Cu.unload(vAPI.getURL('frameModule.js'));
  95. });
  96. /******************************************************************************/
  97. // API matches that of chrome.storage.local:
  98. // https://developer.chrome.com/extensions/storage
  99. vAPI.storage = (function() {
  100. var db = null;
  101. var vacuumTimer = null;
  102. var close = function() {
  103. if ( vacuumTimer !== null ) {
  104. clearTimeout(vacuumTimer);
  105. vacuumTimer = null;
  106. }
  107. if ( db === null ) {
  108. return;
  109. }
  110. db.asyncClose();
  111. db = null;
  112. };
  113. var open = function() {
  114. if ( db !== null ) {
  115. return db;
  116. }
  117. // Create path
  118. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  119. path.append('extension-data');
  120. if ( !path.exists() ) {
  121. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  122. }
  123. if ( !path.isDirectory() ) {
  124. throw Error('Should be a directory...');
  125. }
  126. path.append(location.host + '.sqlite');
  127. // Open database
  128. try {
  129. db = Services.storage.openDatabase(path);
  130. if ( db.connectionReady === false ) {
  131. db.asyncClose();
  132. db = null;
  133. }
  134. } catch (ex) {
  135. }
  136. if ( db === null ) {
  137. return null;
  138. }
  139. // Database was opened, register cleanup task
  140. cleanupTasks.push(close);
  141. // Setup database
  142. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
  143. .executeAsync();
  144. if ( vacuum !== null ) {
  145. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  146. }
  147. return db;
  148. };
  149. // https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
  150. // Vacuum only once, and only while idle
  151. var vacuum = function() {
  152. vacuumTimer = null;
  153. if ( db === null ) {
  154. return;
  155. }
  156. var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
  157. .getService(Ci.nsIIdleService);
  158. if ( idleSvc.idleTime < 60000 ) {
  159. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  160. return;
  161. }
  162. db.createAsyncStatement('VACUUM').executeAsync();
  163. vacuum = null;
  164. };
  165. // Execute a query
  166. var runStatement = function(stmt, callback) {
  167. var result = {};
  168. stmt.executeAsync({
  169. handleResult: function(rows) {
  170. if ( !rows || typeof callback !== 'function' ) {
  171. return;
  172. }
  173. var row;
  174. while ( row = rows.getNextRow() ) {
  175. // we assume that there will be two columns, since we're
  176. // using it only for preferences
  177. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  178. }
  179. },
  180. handleCompletion: function(reason) {
  181. if ( typeof callback === 'function' && reason === 0 ) {
  182. callback(result);
  183. }
  184. },
  185. handleError: function(error) {
  186. console.error('SQLite error ', error.result, error.message);
  187. // Caller expects an answer regardless of failure.
  188. if ( typeof callback === 'function' ) {
  189. callback(null);
  190. }
  191. }
  192. });
  193. };
  194. var bindNames = function(stmt, names) {
  195. if ( Array.isArray(names) === false || names.length === 0 ) {
  196. return;
  197. }
  198. var params = stmt.newBindingParamsArray();
  199. var i = names.length, bp;
  200. while ( i-- ) {
  201. bp = params.newBindingParams();
  202. bp.bindByName('name', names[i]);
  203. params.addParams(bp);
  204. }
  205. stmt.bindParameters(params);
  206. };
  207. var clear = function(callback) {
  208. if ( open() === null ) {
  209. if ( typeof callback === 'function' ) {
  210. callback();
  211. }
  212. return;
  213. }
  214. runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
  215. };
  216. var getBytesInUse = function(keys, callback) {
  217. if ( typeof callback !== 'function' ) {
  218. return;
  219. }
  220. if ( open() === null ) {
  221. callback(0);
  222. return;
  223. }
  224. var stmt;
  225. if ( Array.isArray(keys) ) {
  226. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
  227. bindNames(keys);
  228. } else {
  229. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
  230. }
  231. runStatement(stmt, function(result) {
  232. callback(result.size);
  233. });
  234. };
  235. var read = function(details, callback) {
  236. if ( typeof callback !== 'function' ) {
  237. return;
  238. }
  239. var prepareResult = function(result) {
  240. var key;
  241. for ( key in result ) {
  242. if ( result.hasOwnProperty(key) === false ) {
  243. continue;
  244. }
  245. result[key] = JSON.parse(result[key]);
  246. }
  247. if ( typeof details === 'object' && details !== null ) {
  248. for ( key in details ) {
  249. if ( result.hasOwnProperty(key) === false ) {
  250. result[key] = details[key];
  251. }
  252. }
  253. }
  254. callback(result);
  255. };
  256. if ( open() === null ) {
  257. prepareResult({});
  258. return;
  259. }
  260. var names = [];
  261. if ( details !== null ) {
  262. if ( Array.isArray(details) ) {
  263. names = details;
  264. } else if ( typeof details === 'object' ) {
  265. names = Object.keys(details);
  266. } else {
  267. names = [details.toString()];
  268. }
  269. }
  270. var stmt;
  271. if ( names.length === 0 ) {
  272. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  273. } else {
  274. stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
  275. bindNames(stmt, names);
  276. }
  277. runStatement(stmt, prepareResult);
  278. };
  279. var remove = function(keys, callback) {
  280. if ( open() === null ) {
  281. if ( typeof callback === 'function' ) {
  282. callback();
  283. }
  284. return;
  285. }
  286. var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
  287. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  288. runStatement(stmt, callback);
  289. };
  290. var write = function(details, callback) {
  291. if ( open() === null ) {
  292. if ( typeof callback === 'function' ) {
  293. callback();
  294. }
  295. return;
  296. }
  297. var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
  298. var params = stmt.newBindingParamsArray(), bp;
  299. for ( var key in details ) {
  300. if ( details.hasOwnProperty(key) === false ) {
  301. continue;
  302. }
  303. bp = params.newBindingParams();
  304. bp.bindByName('name', key);
  305. bp.bindByName('value', JSON.stringify(details[key]));
  306. params.addParams(bp);
  307. }
  308. if ( params.length === 0 ) {
  309. return;
  310. }
  311. stmt.bindParameters(params);
  312. runStatement(stmt, callback);
  313. };
  314. // Export API
  315. var api = {
  316. QUOTA_BYTES: 100 * 1024 * 1024,
  317. clear: clear,
  318. get: read,
  319. getBytesInUse: getBytesInUse,
  320. remove: remove,
  321. set: write
  322. };
  323. return api;
  324. })();
  325. /******************************************************************************/
  326. var windowWatcher = {
  327. onReady: function(e) {
  328. if ( e ) {
  329. this.removeEventListener(e.type, windowWatcher.onReady);
  330. }
  331. var wintype = this.document.documentElement.getAttribute('windowtype');
  332. if ( wintype !== 'navigator:browser' ) {
  333. return;
  334. }
  335. var tabBrowser = getTabBrowser(this);
  336. if ( !tabBrowser || !tabBrowser.tabContainer ) {
  337. return;
  338. }
  339. var tabContainer = tabBrowser.tabContainer;
  340. tabContainer.addEventListener('TabClose', tabWatcher.onTabClose);
  341. tabContainer.addEventListener('TabSelect', tabWatcher.onTabSelect);
  342. tabBrowser.addTabsProgressListener(tabWatcher);
  343. vAPI.contextMenu.register(this.document);
  344. // when new window is opened TabSelect doesn't run on the selected tab?
  345. },
  346. observe: function(win, topic) {
  347. if ( topic === 'domwindowopened' ) {
  348. win.addEventListener('DOMContentLoaded', this.onReady);
  349. }
  350. }
  351. };
  352. /******************************************************************************/
  353. var tabWatcher = {
  354. SAME_DOCUMENT: Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT,
  355. onTabClose: function({target}) {
  356. // target is tab in Firefox, browser in Fennec
  357. var tabId = vAPI.tabs.getTabId(target);
  358. if ( tabId === vAPI.noTabId ) {
  359. return;
  360. }
  361. vAPI.tabs.onClosed(tabId);
  362. delete vAPI.toolbarButton.tabs[tabId];
  363. },
  364. onTabSelect: function({target}) {
  365. var tabId = vAPI.tabs.getTabId(target);
  366. if ( tabId === vAPI.noTabId ) {
  367. return;
  368. }
  369. vAPI.setIcon(tabId, getOwnerWindow(target));
  370. },
  371. onLocationChange: function(browser, webProgress, request, location, flags) {
  372. if ( !webProgress.isTopLevel ) {
  373. return;
  374. }
  375. var tabId = vAPI.tabs.getTabId(browser);
  376. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  377. if ( flags & this.SAME_DOCUMENT ) {
  378. vAPI.tabs.onUpdated(tabId, {url: location.asciiSpec}, {
  379. tabId: tabId,
  380. url: browser.currentURI.asciiSpec
  381. });
  382. return;
  383. }
  384. // https://github.com/gorhill/uBlock/issues/105
  385. // Allow any kind of pages
  386. vAPI.tabs.onNavigation({
  387. tabId: tabId,
  388. url: location.asciiSpec
  389. });
  390. }
  391. };
  392. /******************************************************************************/
  393. vAPI.isBehindTheSceneTabId = function(tabId) {
  394. return tabId.toString() === '-1';
  395. };
  396. vAPI.noTabId = '-1';
  397. /******************************************************************************/
  398. var getTabBrowser = function(win) {
  399. return win.gBrowser || null;
  400. };
  401. /******************************************************************************/
  402. var getBrowserForTab = function(tab) {
  403. if ( !tab ) {
  404. return null;
  405. }
  406. return tab.linkedBrowser || null;
  407. };
  408. /******************************************************************************/
  409. var getOwnerWindow = function(target) {
  410. if ( target.ownerDocument ) {
  411. return target.ownerDocument.defaultView;
  412. }
  413. return null;
  414. };
  415. /******************************************************************************/
  416. vAPI.tabs = {};
  417. /******************************************************************************/
  418. vAPI.tabs.registerListeners = function() {
  419. // onNavigation and onUpdated handled with tabWatcher.onLocationChange
  420. // onClosed - handled in tabWatcher.onTabClose
  421. for ( var win of this.getWindows() ) {
  422. windowWatcher.onReady.call(win);
  423. }
  424. Services.ww.registerNotification(windowWatcher);
  425. cleanupTasks.push(function() {
  426. Services.ww.unregisterNotification(windowWatcher);
  427. for ( var win of vAPI.tabs.getWindows() ) {
  428. vAPI.contextMenu.unregister(win.document);
  429. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  430. var tabContainer;
  431. var tabBrowser = getTabBrowser(win);
  432. if ( !tabBrowser ) {
  433. continue;
  434. }
  435. if ( tabBrowser.tabContainer ) {
  436. tabContainer = tabBrowser.tabContainer;
  437. tabBrowser.removeTabsProgressListener(tabWatcher);
  438. }
  439. tabContainer.removeEventListener('TabClose', tabWatcher.onTabClose);
  440. tabContainer.removeEventListener('TabSelect', tabWatcher.onTabSelect);
  441. // Close extension tabs
  442. for ( var tab of tabBrowser.tabs ) {
  443. var browser = getBrowserForTab(tab);
  444. if ( browser === null ) {
  445. continue;
  446. }
  447. var URI = browser.currentURI;
  448. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  449. vAPI.tabs._remove(tab, getTabBrowser(win));
  450. }
  451. }
  452. }
  453. });
  454. };
  455. /******************************************************************************/
  456. vAPI.tabs.stack = new WeakMap();
  457. vAPI.tabs.stackId = 1;
  458. /******************************************************************************/
  459. vAPI.tabs.getTabId = function(target) {
  460. if ( !target ) {
  461. return vAPI.noTabId;
  462. }
  463. if ( target.linkedPanel ) {
  464. target = target.linkedBrowser; // target is a tab
  465. }
  466. if ( target.localName !== 'browser' ) {
  467. return vAPI.noTabId;
  468. }
  469. var tabId = this.stack.get(target);
  470. if ( tabId ) {
  471. return tabId;
  472. }
  473. tabId = '' + this.stackId++;
  474. this.stack.set(target, tabId);
  475. // https://github.com/gorhill/uMatrix/issues/189
  476. // If a new tabid-tab pair is created, tell the client code about it.
  477. if ( this.onNavigation ) {
  478. this.onNavigation({
  479. tabId: tabId,
  480. url: target.currentURI.asciiSpec
  481. });
  482. }
  483. return tabId;
  484. };
  485. /******************************************************************************/
  486. // If tabIds is an array, then an array of tabs will be returned,
  487. // otherwise a single tab
  488. vAPI.tabs.getTabsForIds = function(tabIds) {
  489. var tabs = [];
  490. var singleTab = !Array.isArray(tabIds);
  491. if ( singleTab ) {
  492. tabIds = [tabIds];
  493. }
  494. for ( var tab of this.getAllSync() ) {
  495. var tabId = this.stack.get(getBrowserForTab(tab));
  496. if ( !tabId ) {
  497. continue;
  498. }
  499. if ( tabIds.indexOf(tabId) !== -1 ) {
  500. if ( singleTab ) {
  501. return tab;
  502. }
  503. tabs.push(tab);
  504. }
  505. if ( tabs.length >= tabIds.length ) {
  506. break;
  507. }
  508. }
  509. return tabs.length !== 0 ? tabs : null;
  510. };
  511. /******************************************************************************/
  512. vAPI.tabs.get = function(tabId, callback) {
  513. var tab, win;
  514. if ( tabId === null ) {
  515. win = Services.wm.getMostRecentWindow('navigator:browser');
  516. tab = getTabBrowser(win).selectedTab;
  517. tabId = this.getTabId(tab);
  518. } else {
  519. tab = this.getTabsForIds(tabId);
  520. if ( tab ) {
  521. win = getOwnerWindow(tab);
  522. }
  523. }
  524. // For internal use
  525. if ( typeof callback !== 'function' ) {
  526. return tab;
  527. }
  528. if ( !tab ) {
  529. callback();
  530. return;
  531. }
  532. var windows = this.getWindows();
  533. var browser = getBrowserForTab(tab);
  534. var tabBrowser = getTabBrowser(win);
  535. var tabIndex = tabBrowser.browsers.indexOf(browser);
  536. var tabTitle = tab.label;
  537. callback({
  538. id: tabId,
  539. index: tabIndex,
  540. windowId: windows.indexOf(win),
  541. active: tab === tabBrowser.selectedTab,
  542. url: browser.currentURI.asciiSpec,
  543. title: tabTitle
  544. });
  545. };
  546. /******************************************************************************/
  547. vAPI.tabs.getAllSync = function(window) {
  548. var win, tab;
  549. var tabs = [];
  550. for ( win of this.getWindows() ) {
  551. if ( window && window !== win ) {
  552. continue;
  553. }
  554. var tabBrowser = getTabBrowser(win);
  555. if ( tabBrowser === null ) {
  556. continue;
  557. }
  558. for ( tab of tabBrowser.tabs ) {
  559. tabs.push(tab);
  560. }
  561. }
  562. return tabs;
  563. };
  564. /******************************************************************************/
  565. vAPI.tabs.getAll = function(callback) {
  566. var tabs = [];
  567. var win, tab;
  568. for ( win of this.getWindows() ) {
  569. var tabBrowser = getTabBrowser(win);
  570. if ( tabBrowser === null ) {
  571. continue;
  572. }
  573. for ( tab of tabBrowser.tabs ) {
  574. if ( tab.hasAttribute('pending') ) {
  575. continue;
  576. }
  577. tabs.push({
  578. id: this.getTabId(tab),
  579. url: getBrowserForTab(tab).currentURI.asciiSpec
  580. });
  581. }
  582. }
  583. callback(tabs);
  584. };
  585. /******************************************************************************/
  586. vAPI.tabs.getWindows = function() {
  587. var winumerator = Services.wm.getEnumerator('navigator:browser');
  588. var windows = [];
  589. while ( winumerator.hasMoreElements() ) {
  590. var win = winumerator.getNext();
  591. if ( !win.closed ) {
  592. windows.push(win);
  593. }
  594. }
  595. return windows;
  596. };
  597. /******************************************************************************/
  598. // properties of the details object:
  599. // url: 'URL', // the address that will be opened
  600. // tabId: 1, // the tab is used if set, instead of creating a new one
  601. // index: -1, // undefined: end of the list, -1: following tab, or after index
  602. // active: false, // opens the tab in background - true and undefined: foreground
  603. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  604. vAPI.tabs.open = function(details) {
  605. if ( !details.url ) {
  606. return null;
  607. }
  608. // extension pages
  609. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  610. details.url = vAPI.getURL(details.url);
  611. }
  612. var win, tab, tabBrowser;
  613. if ( details.select ) {
  614. var URI = Services.io.newURI(details.url, null, null);
  615. for ( tab of this.getAllSync() ) {
  616. var browser = getBrowserForTab(tab);
  617. // Or simply .equals if we care about the fragment
  618. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  619. continue;
  620. }
  621. this.select(tab);
  622. return;
  623. }
  624. }
  625. if ( details.active === undefined ) {
  626. details.active = true;
  627. }
  628. if ( details.tabId ) {
  629. tab = this.getTabsForIds(details.tabId);
  630. if ( tab ) {
  631. getBrowserForTab(tab).loadURI(details.url);
  632. return;
  633. }
  634. }
  635. win = Services.wm.getMostRecentWindow('navigator:browser');
  636. tabBrowser = getTabBrowser(win);
  637. if ( details.index === -1 ) {
  638. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  639. }
  640. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  641. if ( details.index !== undefined ) {
  642. tabBrowser.moveTabTo(tab, details.index);
  643. }
  644. };
  645. /******************************************************************************/
  646. // Replace the URL of a tab. Noop if the tab does not exist.
  647. vAPI.tabs.replace = function(tabId, url) {
  648. var targetURL = url;
  649. // extension pages
  650. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  651. targetURL = vAPI.getURL(targetURL);
  652. }
  653. var tab = this.getTabsForIds(tabId);
  654. if ( tab ) {
  655. getBrowserForTab(tab).loadURI(targetURL);
  656. }
  657. };
  658. /******************************************************************************/
  659. vAPI.tabs._remove = function(tab, tabBrowser) {
  660. tabBrowser.removeTab(tab);
  661. };
  662. /******************************************************************************/
  663. vAPI.tabs.remove = function(tabIds) {
  664. if ( !Array.isArray(tabIds) ) {
  665. tabIds = [tabIds];
  666. }
  667. var tabs = this.getTabsForIds(tabIds);
  668. if ( !tabs ) {
  669. return;
  670. }
  671. for ( var tab of tabs ) {
  672. this._remove(tab, getTabBrowser(getOwnerWindow(tab)));
  673. }
  674. };
  675. /******************************************************************************/
  676. vAPI.tabs.reload = function(tabId) {
  677. var tab = this.get(tabId);
  678. if ( !tab ) {
  679. return;
  680. }
  681. getBrowserForTab(tab).webNavigation.reload(
  682. Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE
  683. );
  684. };
  685. /******************************************************************************/
  686. vAPI.tabs.select = function(tab) {
  687. tab = typeof tab === 'object' ? tab : this.get(tab);
  688. if ( !tab ) {
  689. return;
  690. }
  691. getTabBrowser(getOwnerWindow(tab)).selectedTab = tab;
  692. };
  693. /******************************************************************************/
  694. vAPI.tabs.injectScript = function(tabId, details, callback) {
  695. var tab = this.get(tabId);
  696. if ( !tab ) {
  697. return;
  698. }
  699. if ( typeof details.file !== 'string' ) {
  700. return;
  701. }
  702. details.file = vAPI.getURL(details.file);
  703. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  704. location.host + ':broadcast',
  705. JSON.stringify({
  706. broadcast: true,
  707. channelName: 'vAPI',
  708. msg: {
  709. cmd: 'injectScript',
  710. details: details
  711. }
  712. })
  713. );
  714. if ( typeof callback === 'function' ) {
  715. vAPI.setTimeout(callback, 13);
  716. }
  717. };
  718. /******************************************************************************/
  719. vAPI.setIcon = function(tabId, iconId, badge) {
  720. // If badge is undefined, then setIcon was called from the TabSelect event
  721. var win;
  722. if ( badge === undefined ) {
  723. win = iconId;
  724. } else {
  725. win = Services.wm.getMostRecentWindow('navigator:browser');
  726. }
  727. var curTabId = vAPI.tabs.getTabId(getTabBrowser(win).selectedTab);
  728. var tb = vAPI.toolbarButton;
  729. // from 'TabSelect' event
  730. if ( tabId === undefined ) {
  731. tabId = curTabId;
  732. } else if ( badge !== undefined ) {
  733. tb.tabs[tabId] = { badge: badge, img: iconId };
  734. }
  735. if ( tabId === curTabId ) {
  736. tb.updateState(win, tabId);
  737. }
  738. };
  739. /******************************************************************************/
  740. vAPI.messaging = {
  741. get globalMessageManager() {
  742. return Cc['@mozilla.org/globalmessagemanager;1']
  743. .getService(Ci.nsIMessageListenerManager);
  744. },
  745. frameScript: vAPI.getURL('frameScript.js'),
  746. listeners: {},
  747. defaultHandler: null,
  748. NOOPFUNC: function(){},
  749. UNHANDLED: 'vAPI.messaging.notHandled'
  750. };
  751. /******************************************************************************/
  752. vAPI.messaging.listen = function(listenerName, callback) {
  753. this.listeners[listenerName] = callback;
  754. };
  755. /******************************************************************************/
  756. vAPI.messaging.onMessage = function({target, data}) {
  757. var messageManager = target.messageManager;
  758. if ( !messageManager ) {
  759. // Message came from a popup, and its message manager is not usable.
  760. // So instead we broadcast to the parent window.
  761. messageManager = getOwnerWindow(
  762. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  763. ).messageManager;
  764. }
  765. var channelNameRaw = data.channelName;
  766. var pos = channelNameRaw.indexOf('|');
  767. var channelName = channelNameRaw.slice(pos + 1);
  768. var callback = vAPI.messaging.NOOPFUNC;
  769. if ( data.requestId !== undefined ) {
  770. callback = CallbackWrapper.factory(
  771. messageManager,
  772. channelName,
  773. channelNameRaw.slice(0, pos),
  774. data.requestId
  775. ).callback;
  776. }
  777. var sender = {
  778. tab: {
  779. id: vAPI.tabs.getTabId(target)
  780. }
  781. };
  782. // Specific handler
  783. var r = vAPI.messaging.UNHANDLED;
  784. var listener = vAPI.messaging.listeners[channelName];
  785. if ( typeof listener === 'function' ) {
  786. r = listener(data.msg, sender, callback);
  787. }
  788. if ( r !== vAPI.messaging.UNHANDLED ) {
  789. return;
  790. }
  791. // Default handler
  792. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  793. if ( r !== vAPI.messaging.UNHANDLED ) {
  794. return;
  795. }
  796. console.error('uMatrix> messaging > unknown request: %o', data);
  797. // Unhandled:
  798. // Need to callback anyways in case caller expected an answer, or
  799. // else there is a memory leak on caller's side
  800. callback();
  801. };
  802. /******************************************************************************/
  803. vAPI.messaging.setup = function(defaultHandler) {
  804. // Already setup?
  805. if ( this.defaultHandler !== null ) {
  806. return;
  807. }
  808. if ( typeof defaultHandler !== 'function' ) {
  809. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  810. }
  811. this.defaultHandler = defaultHandler;
  812. this.globalMessageManager.addMessageListener(
  813. location.host + ':background',
  814. this.onMessage
  815. );
  816. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  817. cleanupTasks.push(function() {
  818. var gmm = vAPI.messaging.globalMessageManager;
  819. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  820. gmm.removeMessageListener(
  821. location.host + ':background',
  822. vAPI.messaging.onMessage
  823. );
  824. });
  825. };
  826. /******************************************************************************/
  827. vAPI.messaging.broadcast = function(message) {
  828. this.globalMessageManager.broadcastAsyncMessage(
  829. location.host + ':broadcast',
  830. JSON.stringify({broadcast: true, msg: message})
  831. );
  832. };
  833. /******************************************************************************/
  834. // This allows to avoid creating a closure for every single message which
  835. // expects an answer. Having a closure created each time a message is processed
  836. // has been always bothering me. Another benefit of the implementation here
  837. // is to reuse the callback proxy object, so less memory churning.
  838. //
  839. // https://developers.google.com/speed/articles/optimizing-javascript
  840. // "Creating a closure is significantly slower then creating an inner
  841. // function without a closure, and much slower than reusing a static
  842. // function"
  843. //
  844. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  845. // "the dreaded 'uniformly slow code' case where every function takes 1%
  846. // of CPU and you have to make one hundred separate performance optimizations
  847. // to improve performance at all"
  848. //
  849. // http://jsperf.com/closure-no-closure/2
  850. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  851. this.callback = this.proxy.bind(this); // bind once
  852. this.init(messageManager, channelName, listenerId, requestId);
  853. };
  854. CallbackWrapper.junkyard = [];
  855. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  856. var wrapper = CallbackWrapper.junkyard.pop();
  857. if ( wrapper ) {
  858. wrapper.init(messageManager, channelName, listenerId, requestId);
  859. return wrapper;
  860. }
  861. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  862. };
  863. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  864. this.messageManager = messageManager;
  865. this.channelName = channelName;
  866. this.listenerId = listenerId;
  867. this.requestId = requestId;
  868. };
  869. CallbackWrapper.prototype.proxy = function(response) {
  870. var message = JSON.stringify({
  871. requestId: this.requestId,
  872. channelName: this.channelName,
  873. msg: response !== undefined ? response : null
  874. });
  875. if ( this.messageManager.sendAsyncMessage ) {
  876. this.messageManager.sendAsyncMessage(this.listenerId, message);
  877. } else {
  878. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  879. }
  880. // Mark for reuse
  881. this.messageManager =
  882. this.channelName =
  883. this.requestId =
  884. this.listenerId = null;
  885. CallbackWrapper.junkyard.push(this);
  886. };
  887. /******************************************************************************/
  888. var httpRequestHeadersFactory = function(channel) {
  889. var entry = httpRequestHeadersFactory.junkyard.pop();
  890. if ( entry ) {
  891. return entry.init(channel);
  892. }
  893. return new HTTPRequestHeaders(channel);
  894. };
  895. httpRequestHeadersFactory.junkyard = [];
  896. var HTTPRequestHeaders = function(channel) {
  897. this.init(channel);
  898. };
  899. HTTPRequestHeaders.prototype.init = function(channel) {
  900. this.channel = channel;
  901. return this;
  902. };
  903. HTTPRequestHeaders.prototype.dispose = function() {
  904. this.channel = null;
  905. httpRequestHeadersFactory.junkyard.push(this);
  906. };
  907. HTTPRequestHeaders.prototype.getHeader = function(name) {
  908. try {
  909. return this.channel.getRequestHeader(name);
  910. } catch (e) {
  911. }
  912. return '';
  913. };
  914. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  915. var oldValue = this.getHeader(name);
  916. if ( newValue === oldValue ) {
  917. return false;
  918. }
  919. if ( oldValue === '' && create !== true ) {
  920. return false;
  921. }
  922. this.channel.setRequestHeader(name, newValue, false);
  923. return true;
  924. };
  925. /******************************************************************************/
  926. var httpObserver = {
  927. classDescription: 'net-channel-event-sinks for ' + location.host,
  928. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  929. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  930. REQDATAKEY: location.host + 'reqdata',
  931. ABORT: Components.results.NS_BINDING_ABORTED,
  932. ACCEPT: Components.results.NS_SUCCEEDED,
  933. // Request types:
  934. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  935. frameTypeMap: {
  936. 6: 'main_frame',
  937. 7: 'sub_frame'
  938. },
  939. typeMap: {
  940. 1: 'other',
  941. 2: 'script',
  942. 3: 'image',
  943. 4: 'stylesheet',
  944. 5: 'object',
  945. 6: 'main_frame',
  946. 7: 'sub_frame',
  947. 10: 'ping',
  948. 11: 'xmlhttprequest',
  949. 12: 'object',
  950. 14: 'font',
  951. 15: 'media',
  952. 16: 'websocket',
  953. 21: 'image'
  954. },
  955. mimeTypeMap: {
  956. 'audio': 15,
  957. 'video': 15
  958. },
  959. get componentRegistrar() {
  960. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  961. },
  962. get categoryManager() {
  963. return Cc['@mozilla.org/categorymanager;1']
  964. .getService(Ci.nsICategoryManager);
  965. },
  966. QueryInterface: (function() {
  967. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  968. return XPCOMUtils.generateQI([
  969. Ci.nsIFactory,
  970. Ci.nsIObserver,
  971. Ci.nsIChannelEventSink,
  972. Ci.nsISupportsWeakReference
  973. ]);
  974. })(),
  975. createInstance: function(outer, iid) {
  976. if ( outer ) {
  977. throw Components.results.NS_ERROR_NO_AGGREGATION;
  978. }
  979. return this.QueryInterface(iid);
  980. },
  981. register: function() {
  982. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  983. Services.obs.addObserver(this, 'http-on-opening-request', true);
  984. Services.obs.addObserver(this, 'http-on-modify-request', true);
  985. Services.obs.addObserver(this, 'http-on-examine-response', true);
  986. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  987. // Guard against stale instances not having been unregistered
  988. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  989. try {
  990. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  991. } catch (ex) {
  992. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  993. }
  994. }
  995. this.componentRegistrar.registerFactory(
  996. this.classID,
  997. this.classDescription,
  998. this.contractID,
  999. this
  1000. );
  1001. this.categoryManager.addCategoryEntry(
  1002. 'net-channel-event-sinks',
  1003. this.contractID,
  1004. this.contractID,
  1005. false,
  1006. true
  1007. );
  1008. },
  1009. unregister: function() {
  1010. Services.obs.removeObserver(this, 'http-on-opening-request');
  1011. Services.obs.removeObserver(this, 'http-on-modify-request');
  1012. Services.obs.removeObserver(this, 'http-on-examine-response');
  1013. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1014. this.componentRegistrar.unregisterFactory(this.classID, this);
  1015. this.categoryManager.deleteCategoryEntry(
  1016. 'net-channel-event-sinks',
  1017. this.contractID,
  1018. false
  1019. );
  1020. },
  1021. handleRequest: function(channel, URI, tabId, rawtype) {
  1022. var type = this.typeMap[rawtype] || 'other';
  1023. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1024. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  1025. return false;
  1026. }
  1027. var result = onBeforeRequest.callback({
  1028. hostname: URI.asciiHost,
  1029. parentFrameId: type === 'main_frame' ? -1 : 0,
  1030. tabId: tabId,
  1031. type: type,
  1032. url: URI.asciiSpec
  1033. });
  1034. if ( typeof result !== 'object' ) {
  1035. return false;
  1036. }
  1037. channel.cancel(this.ABORT);
  1038. return true;
  1039. },
  1040. handleRequestHeaders: function(channel, URI, tabId, rawtype) {
  1041. var type = this.typeMap[rawtype] || 'other';
  1042. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1043. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  1044. return;
  1045. }
  1046. var requestHeaders = httpRequestHeadersFactory(channel);
  1047. onBeforeSendHeaders.callback({
  1048. hostname: URI.asciiHost,
  1049. parentFrameId: type === 'main_frame' ? -1 : 0,
  1050. requestHeaders: requestHeaders,
  1051. tabId: tabId,
  1052. type: type,
  1053. url: URI.asciiSpec
  1054. });
  1055. requestHeaders.dispose();
  1056. },
  1057. channelDataFromChannel: function(channel) {
  1058. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1059. try {
  1060. return channel.getProperty(this.REQDATAKEY);
  1061. } catch (ex) {
  1062. }
  1063. }
  1064. return null;
  1065. },
  1066. // https://github.com/gorhill/uMatrix/issues/165
  1067. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1068. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1069. // care about embedded frames topography.
  1070. // Also:
  1071. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1072. tabIdFromChannel: function(channel) {
  1073. var aWindow;
  1074. if ( channel.notificationCallbacks ) {
  1075. try {
  1076. var loadContext = channel
  1077. .notificationCallbacks
  1078. .getInterface(Ci.nsILoadContext);
  1079. if ( loadContext.topFrameElement ) {
  1080. return vAPI.tabs.getTabId(loadContext.topFrameElement);
  1081. }
  1082. aWindow = loadContext.associatedWindow;
  1083. } catch (ex) {
  1084. //console.error(ex);
  1085. }
  1086. }
  1087. try {
  1088. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  1089. aWindow = channel
  1090. .loadGroup
  1091. .notificationCallbacks
  1092. .getInterface(Ci.nsILoadContext)
  1093. .associatedWindow;
  1094. }
  1095. if ( aWindow ) {
  1096. return vAPI.tabs.getTabId(aWindow
  1097. .getInterface(Ci.nsIWebNavigation)
  1098. .QueryInterface(Ci.nsIDocShell)
  1099. .rootTreeItem
  1100. .QueryInterface(Ci.nsIInterfaceRequestor)
  1101. .getInterface(Ci.nsIDOMWindow)
  1102. .gBrowser
  1103. .getBrowserForContentWindow(aWindow)
  1104. );
  1105. }
  1106. } catch (ex) {
  1107. //console.error(ex);
  1108. }
  1109. return vAPI.noTabId;
  1110. },
  1111. rawtypeFromContentType: function(channel) {
  1112. var mime = channel.contentType;
  1113. if ( !mime ) {
  1114. return 0;
  1115. }
  1116. var pos = mime.indexOf('/');
  1117. if ( pos === -1 ) {
  1118. pos = mime.length;
  1119. }
  1120. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1121. },
  1122. observe: function(channel, topic) {
  1123. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1124. return;
  1125. }
  1126. var URI = channel.URI;
  1127. var channelData, tabId, rawtype;
  1128. if (
  1129. topic === 'http-on-examine-response' ||
  1130. topic === 'http-on-examine-cached-response'
  1131. ) {
  1132. channelData = this.channelDataFromChannel(channel);
  1133. if ( channelData === null ) {
  1134. return;
  1135. }
  1136. var type = this.frameTypeMap[channelData[1]];
  1137. if ( !type ) {
  1138. return;
  1139. }
  1140. topic = 'Content-Security-Policy';
  1141. var result;
  1142. try {
  1143. result = channel.getResponseHeader(topic);
  1144. } catch (ex) {
  1145. result = null;
  1146. }
  1147. result = vAPI.net.onHeadersReceived.callback({
  1148. hostname: URI.asciiHost,
  1149. parentFrameId: type === 'main_frame' ? -1 : 0,
  1150. responseHeaders: result ? [{name: topic, value: result}] : [],
  1151. tabId: channelData[0],
  1152. type: type,
  1153. url: URI.asciiSpec
  1154. });
  1155. if ( result ) {
  1156. channel.setResponseHeader(
  1157. topic,
  1158. result.responseHeaders.pop().value,
  1159. true
  1160. );
  1161. }
  1162. return;
  1163. }
  1164. if ( topic === 'http-on-modify-request' ) {
  1165. channelData = this.channelDataFromChannel(channel);
  1166. if ( channelData === null ) {
  1167. return;
  1168. }
  1169. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1170. return;
  1171. }
  1172. // http-on-opening-request
  1173. tabId = this.tabIdFromChannel(channel);
  1174. rawtype = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1175. if ( this.handleRequest(channel, URI, tabId, rawtype) === true ) {
  1176. return;
  1177. }
  1178. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1179. return;
  1180. }
  1181. // Carry data for behind-the-scene redirects
  1182. channel.setProperty(this.REQDATAKEY, [tabId, rawtype]);
  1183. },
  1184. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1185. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1186. var result = this.ACCEPT;
  1187. // If error thrown, the redirect will fail
  1188. try {
  1189. var URI = newChannel.URI;
  1190. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1191. return;
  1192. }
  1193. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1194. return;
  1195. }
  1196. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1197. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1198. result = this.ABORT;
  1199. return;
  1200. }
  1201. // Carry the data on in case of multiple redirects
  1202. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1203. newChannel.setProperty(this.REQDATAKEY, channelData);
  1204. }
  1205. } catch (ex) {
  1206. // console.error(ex);
  1207. } finally {
  1208. callback.onRedirectVerifyCallback(result);
  1209. }
  1210. }
  1211. };
  1212. /******************************************************************************/
  1213. vAPI.net = {};
  1214. /******************************************************************************/
  1215. vAPI.net.registerListeners = function() {
  1216. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1217. new Set(this.onBeforeRequest.types) :
  1218. null;
  1219. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1220. new Set(this.onBeforeSendHeaders.types) :
  1221. null;
  1222. httpObserver.register();
  1223. cleanupTasks.push(function() {
  1224. httpObserver.unregister();
  1225. });
  1226. };
  1227. /******************************************************************************/
  1228. vAPI.toolbarButton = {
  1229. id: location.host + '-button',
  1230. type: 'view',
  1231. viewId: location.host + '-panel',
  1232. label: vAPI.app.name,
  1233. tooltiptext: vAPI.app.name,
  1234. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1235. };
  1236. /******************************************************************************/
  1237. // Toolbar button UI for desktop Firefox
  1238. vAPI.toolbarButton.init = function() {
  1239. var CustomizableUI;
  1240. try {
  1241. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1242. } catch (ex) {
  1243. return;
  1244. }
  1245. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1246. this.styleURI = [
  1247. '#' + this.id + ' {',
  1248. 'list-style-image: url(',
  1249. vAPI.getURL('img/browsericons/icon19-off.png'),
  1250. ');',
  1251. '}',
  1252. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1253. 'width: 160px;',
  1254. 'height: 290px;',
  1255. 'overflow: hidden !important;',
  1256. '}'
  1257. ];
  1258. var platformVersion = Services.appinfo.platformVersion;
  1259. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1260. this.styleURI.push(
  1261. '#' + this.id + '[badge]:not([badge=""])::after {',
  1262. 'position: absolute;',
  1263. 'margin-left: -16px;',
  1264. 'margin-top: 3px;',
  1265. 'padding: 1px 2px;',
  1266. 'font-size: 9px;',
  1267. 'font-weight: bold;',
  1268. 'color: #fff;',
  1269. 'background: #000;',
  1270. 'content: attr(badge);',
  1271. '}'
  1272. );
  1273. } else {
  1274. this.CUIEvents = {};
  1275. var updateBadge = function() {
  1276. var wId = vAPI.toolbarButton.id;
  1277. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1278. for ( var win of vAPI.tabs.getWindows() ) {
  1279. var button = win.document.getElementById(wId);
  1280. if ( buttonInPanel ) {
  1281. button.classList.remove('badged-button');
  1282. continue;
  1283. }
  1284. if ( button === null ) {
  1285. continue;
  1286. }
  1287. button.classList.add('badged-button');
  1288. }
  1289. if ( buttonInPanel ) {
  1290. return;
  1291. }
  1292. // Anonymous elements need some time to be reachable
  1293. vAPI.setTimeout(this.updateBadgeStyle, 250);
  1294. }.bind(this.CUIEvents);
  1295. this.CUIEvents.onCustomizeEnd = updateBadge;
  1296. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1297. this.CUIEvents.updateBadgeStyle = function() {
  1298. var css = [
  1299. 'background: #000',
  1300. 'color: #fff'
  1301. ].join(';');
  1302. for ( var win of vAPI.tabs.getWindows() ) {
  1303. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1304. if ( button === null ) {
  1305. continue;
  1306. }
  1307. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1308. button,
  1309. 'class',
  1310. 'toolbarbutton-badge'
  1311. );
  1312. if ( !badge ) {
  1313. return;
  1314. }
  1315. badge.style.cssText = css;
  1316. }
  1317. };
  1318. this.onCreated = function(button) {
  1319. button.setAttribute('badge', '');
  1320. vAPI.setTimeout(updateBadge, 250);
  1321. };
  1322. CustomizableUI.addListener(this.CUIEvents);
  1323. }
  1324. this.styleURI = Services.io.newURI(
  1325. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1326. null,
  1327. null
  1328. );
  1329. this.closePopup = function({target}) {
  1330. CustomizableUI.hidePanelForNode(
  1331. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1332. );
  1333. };
  1334. CustomizableUI.createWidget(this);
  1335. vAPI.messaging.globalMessageManager.addMessageListener(
  1336. location.host + ':closePopup',
  1337. this.closePopup
  1338. );
  1339. cleanupTasks.push(function() {
  1340. if ( this.CUIEvents ) {
  1341. CustomizableUI.removeListener(this.CUIEvents);
  1342. }
  1343. CustomizableUI.destroyWidget(this.id);
  1344. vAPI.messaging.globalMessageManager.removeMessageListener(
  1345. location.host + ':closePopup',
  1346. this.closePopup
  1347. );
  1348. for ( var win of vAPI.tabs.getWindows() ) {
  1349. var panel = win.document.getElementById(this.viewId);
  1350. panel.parentNode.removeChild(panel);
  1351. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1352. .getInterface(Ci.nsIDOMWindowUtils)
  1353. .removeSheet(this.styleURI, 1);
  1354. }
  1355. }.bind(this));
  1356. this.init = null;
  1357. };
  1358. /******************************************************************************/
  1359. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1360. var panel = doc.createElement('panelview');
  1361. panel.setAttribute('id', this.viewId);
  1362. var iframe = doc.createElement('iframe');
  1363. iframe.setAttribute('type', 'content');
  1364. iframe.setAttribute('overflow-x', 'hidden');
  1365. doc.getElementById('PanelUI-multiView')
  1366. .appendChild(panel)
  1367. .appendChild(iframe);
  1368. var scrollBarWidth = 0;
  1369. var updateTimer = null;
  1370. var delayedResize = function() {
  1371. if ( updateTimer ) {
  1372. return;
  1373. }
  1374. updateTimer = vAPI.setTimeout(resizePopup, 10);
  1375. };
  1376. var resizePopup = function() {
  1377. updateTimer = null;
  1378. var body = iframe.contentDocument.body;
  1379. panel.parentNode.style.maxWidth = 'none';
  1380. // We set a limit for height
  1381. var height = Math.min(body.clientHeight, 600);
  1382. // https://github.com/chrisaljoudi/uBlock/issues/730
  1383. // Voodoo programming: this recipe works
  1384. panel.style.setProperty('height', height + 'px');
  1385. iframe.style.setProperty('height', height + 'px');
  1386. // Adjust width for presence/absence of vertical scroll bar which may
  1387. // have appeared as a result of last operation.
  1388. var contentWindow = iframe.contentWindow;
  1389. var width = body.clientWidth;
  1390. if ( contentWindow.scrollMaxY !== 0 ) {
  1391. width += scrollBarWidth;
  1392. }
  1393. panel.style.setProperty('width', width + 'px');
  1394. // scrollMaxX should always be zero once we know the scrollbar width
  1395. if ( contentWindow.scrollMaxX !== 0 ) {
  1396. scrollBarWidth = contentWindow.scrollMaxX;
  1397. width += scrollBarWidth;
  1398. panel.style.setProperty('width', width + 'px');
  1399. }
  1400. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1401. delayedResize();
  1402. return;
  1403. }
  1404. };
  1405. var onPopupReady = function() {
  1406. var win = this.contentWindow;
  1407. if ( !win || win.location.host !== location.host ) {
  1408. return;
  1409. }
  1410. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1411. attributes: true,
  1412. characterData: true,
  1413. subtree: true
  1414. });
  1415. delayedResize();
  1416. };
  1417. iframe.addEventListener('load', onPopupReady, true);
  1418. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1419. .getInterface(Ci.nsIDOMWindowUtils)
  1420. .loadSheet(this.styleURI, 1);
  1421. };
  1422. /******************************************************************************/
  1423. vAPI.toolbarButton.onViewShowing = function({target}) {
  1424. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1425. };
  1426. /******************************************************************************/
  1427. vAPI.toolbarButton.onViewHiding = function({target}) {
  1428. target.parentNode.style.maxWidth = '';
  1429. target.firstChild.setAttribute('src', 'about:blank');
  1430. };
  1431. /******************************************************************************/
  1432. vAPI.toolbarButton.updateState = function(win, tabId) {
  1433. var button = win.document.getElementById(this.id);
  1434. if ( !button ) {
  1435. return;
  1436. }
  1437. var icon = this.tabs[tabId];
  1438. button.setAttribute('badge', icon && icon.badge || '');
  1439. var iconId = icon && icon.img ? icon.img : 'off';
  1440. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1441. button.style.listStyleImage = icon;
  1442. };
  1443. /******************************************************************************/
  1444. vAPI.toolbarButton.init();
  1445. /******************************************************************************/
  1446. /******************************************************************************/
  1447. vAPI.contextMenu = {
  1448. contextMap: {
  1449. frame: 'inFrame',
  1450. link: 'onLink',
  1451. image: 'onImage',
  1452. audio: 'onAudio',
  1453. video: 'onVideo',
  1454. editable: 'onEditableArea'
  1455. }
  1456. };
  1457. /******************************************************************************/
  1458. vAPI.contextMenu.displayMenuItem = function({target}) {
  1459. var doc = target.ownerDocument;
  1460. var gContextMenu = doc.defaultView.gContextMenu;
  1461. if ( !gContextMenu.browser ) {
  1462. return;
  1463. }
  1464. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1465. var currentURI = gContextMenu.browser.currentURI;
  1466. // https://github.com/chrisaljoudi/uBlock/issues/105
  1467. // TODO: Should the element picker works on any kind of pages?
  1468. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1469. menuitem.hidden = true;
  1470. return;
  1471. }
  1472. var ctx = vAPI.contextMenu.contexts;
  1473. if ( !ctx ) {
  1474. menuitem.hidden = false;
  1475. return;
  1476. }
  1477. var ctxMap = vAPI.contextMenu.contextMap;
  1478. for ( var context of ctx ) {
  1479. if (
  1480. context === 'page' &&
  1481. !gContextMenu.onLink &&
  1482. !gContextMenu.onImage &&
  1483. !gContextMenu.onEditableArea &&
  1484. !gContextMenu.inFrame &&
  1485. !gContextMenu.onVideo &&
  1486. !gContextMenu.onAudio
  1487. ) {
  1488. menuitem.hidden = false;
  1489. return;
  1490. }
  1491. if ( gContextMenu[ctxMap[context]] ) {
  1492. menuitem.hidden = false;
  1493. return;
  1494. }
  1495. }
  1496. menuitem.hidden = true;
  1497. };
  1498. /******************************************************************************/
  1499. vAPI.contextMenu.register = function(doc) {
  1500. if ( !this.menuItemId ) {
  1501. return;
  1502. }
  1503. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1504. var menuitem = doc.createElement('menuitem');
  1505. menuitem.setAttribute('id', this.menuItemId);
  1506. menuitem.setAttribute('label', this.menuLabel);
  1507. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1508. menuitem.setAttribute('class', 'menuitem-iconic');
  1509. menuitem.addEventListener('command', this.onCommand);
  1510. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1511. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1512. };
  1513. /******************************************************************************/
  1514. vAPI.contextMenu.unregister = function(doc) {
  1515. if ( !this.menuItemId ) {
  1516. return;
  1517. }
  1518. var menuitem = doc.getElementById(this.menuItemId);
  1519. var contextMenu = menuitem.parentNode;
  1520. menuitem.removeEventListener('command', this.onCommand);
  1521. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1522. contextMenu.removeChild(menuitem);
  1523. };
  1524. /******************************************************************************/
  1525. vAPI.contextMenu.create = function(details, callback) {
  1526. this.menuItemId = details.id;
  1527. this.menuLabel = details.title;
  1528. this.contexts = details.contexts;
  1529. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1530. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1531. } else {
  1532. // default in Chrome
  1533. this.contexts = ['page'];
  1534. }
  1535. this.onCommand = function() {
  1536. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1537. var details = {
  1538. menuItemId: this.id
  1539. };
  1540. if ( gContextMenu.inFrame ) {
  1541. details.tagName = 'iframe';
  1542. // Probably won't work with e10s
  1543. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1544. } else if ( gContextMenu.onImage ) {
  1545. details.tagName = 'img';
  1546. details.srcUrl = gContextMenu.mediaURL;
  1547. } else if ( gContextMenu.onAudio ) {
  1548. details.tagName = 'audio';
  1549. details.srcUrl = gContextMenu.mediaURL;
  1550. } else if ( gContextMenu.onVideo ) {
  1551. details.tagName = 'video';
  1552. details.srcUrl = gContextMenu.mediaURL;
  1553. } else if ( gContextMenu.onLink ) {
  1554. details.tagName = 'a';
  1555. details.linkUrl = gContextMenu.linkURL;
  1556. }
  1557. callback(details, {
  1558. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1559. url: gContextMenu.browser.currentURI.asciiSpec
  1560. });
  1561. };
  1562. for ( var win of vAPI.tabs.getWindows() ) {
  1563. this.register(win.document);
  1564. }
  1565. };
  1566. /******************************************************************************/
  1567. vAPI.contextMenu.remove = function() {
  1568. for ( var win of vAPI.tabs.getWindows() ) {
  1569. this.unregister(win.document);
  1570. }
  1571. this.menuItemId = null;
  1572. this.menuLabel = null;
  1573. this.contexts = null;
  1574. this.onCommand = null;
  1575. };
  1576. /******************************************************************************/
  1577. /******************************************************************************/
  1578. var optionsObserver = {
  1579. addonId: 'uMatrix@raymondhill.net',
  1580. register: function() {
  1581. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1582. cleanupTasks.push(this.unregister.bind(this));
  1583. var browser = getBrowserForTab(vAPI.tabs.get(null));
  1584. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1585. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1586. }
  1587. },
  1588. unregister: function() {
  1589. Services.obs.removeObserver(this, 'addon-options-displayed');
  1590. },
  1591. setupOptionsButton: function(doc, id, page) {
  1592. var button = doc.getElementById(id);
  1593. if ( button === null ) {
  1594. return;
  1595. }
  1596. button.addEventListener('command', function() {
  1597. vAPI.tabs.open({ url: page, index: -1 });
  1598. });
  1599. button.label = vAPI.i18n(id);
  1600. },
  1601. observe: function(doc, topic, addonId) {
  1602. if ( addonId !== this.addonId ) {
  1603. return;
  1604. }
  1605. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1606. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  1607. }
  1608. };
  1609. optionsObserver.register();
  1610. /******************************************************************************/
  1611. /******************************************************************************/
  1612. vAPI.lastError = function() {
  1613. return null;
  1614. };
  1615. /******************************************************************************/
  1616. /******************************************************************************/
  1617. // This is called only once, when everything has been loaded in memory after
  1618. // the extension was launched. It can be used to inject content scripts
  1619. // in already opened web pages, to remove whatever nuisance could make it to
  1620. // the web pages before uBlock was ready.
  1621. vAPI.onLoadAllCompleted = function() {
  1622. for ( var tab of this.tabs.getAllSync() ) {
  1623. // We're insterested in only the tabs that were already loaded
  1624. if ( tab.hasAttribute('pending') ) {
  1625. continue;
  1626. }
  1627. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  1628. location.host + '-load-completed'
  1629. );
  1630. }
  1631. };
  1632. /******************************************************************************/
  1633. /******************************************************************************/
  1634. // Likelihood is that we do not have to punycode: given punycode overhead,
  1635. // it's faster to check and skip than do it unconditionally all the time.
  1636. var punycodeHostname = punycode.toASCII;
  1637. var isNotASCII = /[^\x21-\x7F]/;
  1638. vAPI.punycodeHostname = function(hostname) {
  1639. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1640. };
  1641. vAPI.punycodeURL = function(url) {
  1642. if ( isNotASCII.test(url) ) {
  1643. return Services.io.newURI(url, null, null).asciiSpec;
  1644. }
  1645. return url;
  1646. };
  1647. /******************************************************************************/
  1648. /******************************************************************************/
  1649. vAPI.browserData = {};
  1650. /******************************************************************************/
  1651. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  1652. vAPI.browserData.clearCache = function(callback) {
  1653. // PURGE_DISK_DATA_ONLY:1
  1654. // PURGE_DISK_ALL:2
  1655. // PURGE_EVERYTHING:3
  1656. // However I verified that not argument does clear the cache data.
  1657. Services.cache2.clear();
  1658. if ( typeof callback === 'function' ) {
  1659. callback();
  1660. }
  1661. };
  1662. /******************************************************************************/
  1663. vAPI.browserData.clearOrigin = function(/* domain */) {
  1664. // TODO
  1665. };
  1666. /******************************************************************************/
  1667. /******************************************************************************/
  1668. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  1669. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  1670. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  1671. vAPI.cookies = {};
  1672. /******************************************************************************/
  1673. vAPI.cookies.CookieEntry = function(ffCookie) {
  1674. this.domain = ffCookie.host;
  1675. this.name = ffCookie.name;
  1676. this.path = ffCookie.path;
  1677. this.secure = ffCookie.isSecure === true;
  1678. this.session = ffCookie.expires === 0;
  1679. this.value = ffCookie.value;
  1680. };
  1681. /******************************************************************************/
  1682. vAPI.cookies.start = function() {
  1683. Services.obs.addObserver(this, 'cookie-changed', false);
  1684. cleanupTasks.push(this.stop.bind(this));
  1685. };
  1686. /******************************************************************************/
  1687. vAPI.cookies.stop = function() {
  1688. Services.obs.removeObserver(this, 'cookie-changed');
  1689. };
  1690. /******************************************************************************/
  1691. vAPI.cookies.observe = function(subject, topic, reason) {
  1692. if ( topic !== 'cookie-changed' ) {
  1693. return;
  1694. }
  1695. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  1696. return;
  1697. }
  1698. if ( typeof this.onChanged === 'function' ) {
  1699. this.onChanged(new this.CookieEntry(subject));
  1700. }
  1701. };
  1702. /******************************************************************************/
  1703. // Meant and expected to be asynchronous.
  1704. vAPI.cookies.getAll = function(callback) {
  1705. if ( typeof callback !== 'function' ) {
  1706. return;
  1707. }
  1708. var onAsync = function() {
  1709. var out = [];
  1710. var enumerator = Services.cookies.enumerator;
  1711. var ffcookie;
  1712. while ( enumerator.hasMoreElements() ) {
  1713. ffcookie = enumerator.getNext();
  1714. if ( ffcookie instanceof Ci.nsICookie ) {
  1715. out.push(new this.CookieEntry(ffcookie));
  1716. }
  1717. }
  1718. callback(out);
  1719. };
  1720. vAPI.setTimeout(onAsync.bind(this), 0);
  1721. };
  1722. /******************************************************************************/
  1723. vAPI.cookies.remove = function(details, callback) {
  1724. var uri = Services.io.newURI(details.url, null, null);
  1725. var cookies = Services.cookies;
  1726. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  1727. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  1728. if ( typeof callback === 'function' ) {
  1729. callback({
  1730. domain: uri.asciiHost,
  1731. name: details.name,
  1732. path: uri.path
  1733. });
  1734. }
  1735. };
  1736. /******************************************************************************/
  1737. /******************************************************************************/
  1738. })();
  1739. /******************************************************************************/