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.

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