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.

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