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.

1952 lines
57 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. 21: 'image'
  808. },
  809. lastRequest: [{}, {}],
  810. get componentRegistrar() {
  811. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  812. },
  813. get categoryManager() {
  814. return Cc['@mozilla.org/categorymanager;1']
  815. .getService(Ci.nsICategoryManager);
  816. },
  817. QueryInterface: (function() {
  818. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  819. return XPCOMUtils.generateQI([
  820. Ci.nsIFactory,
  821. Ci.nsIObserver,
  822. Ci.nsIChannelEventSink,
  823. Ci.nsISupportsWeakReference
  824. ]);
  825. })(),
  826. createInstance: function(outer, iid) {
  827. if ( outer ) {
  828. throw Components.results.NS_ERROR_NO_AGGREGATION;
  829. }
  830. return this.QueryInterface(iid);
  831. },
  832. register: function() {
  833. Services.obs.addObserver(this, 'http-on-opening-request', true);
  834. Services.obs.addObserver(this, 'http-on-examine-response', true);
  835. // Guard against stale instances not having been unregistered
  836. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  837. try {
  838. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  839. } catch (ex) {
  840. console.error('uBlock> httpObserver > unable to unregister stale instance: ', ex);
  841. }
  842. }
  843. this.componentRegistrar.registerFactory(
  844. this.classID,
  845. this.classDescription,
  846. this.contractID,
  847. this
  848. );
  849. this.categoryManager.addCategoryEntry(
  850. 'net-channel-event-sinks',
  851. this.contractID,
  852. this.contractID,
  853. false,
  854. true
  855. );
  856. },
  857. unregister: function() {
  858. Services.obs.removeObserver(this, 'http-on-opening-request');
  859. Services.obs.removeObserver(this, 'http-on-examine-response');
  860. this.componentRegistrar.unregisterFactory(this.classID, this);
  861. this.categoryManager.deleteCategoryEntry(
  862. 'net-channel-event-sinks',
  863. this.contractID,
  864. false
  865. );
  866. },
  867. handlePopup: function(URI, tabId, sourceTabId) {
  868. if ( !sourceTabId ) {
  869. return false;
  870. }
  871. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  872. return false;
  873. }
  874. var result = vAPI.tabs.onPopup({
  875. targetTabId: tabId,
  876. openerTabId: sourceTabId,
  877. targetURL: URI.asciiSpec
  878. });
  879. return result === true;
  880. },
  881. handleRequest: function(channel, URI, details) {
  882. var onBeforeRequest = vAPI.net.onBeforeRequest;
  883. var type = this.typeMap[details.type] || 'other';
  884. if ( onBeforeRequest.types.has(type) === false ) {
  885. return false;
  886. }
  887. var result = onBeforeRequest.callback({
  888. frameId: details.frameId,
  889. hostname: URI.asciiHost,
  890. parentFrameId: details.parentFrameId,
  891. tabId: details.tabId,
  892. type: type,
  893. url: URI.asciiSpec
  894. });
  895. if ( !result || typeof result !== 'object' ) {
  896. return false;
  897. }
  898. if ( result.cancel === true ) {
  899. channel.cancel(this.ABORT);
  900. return true;
  901. }
  902. /*if ( result.redirectUrl ) {
  903. channel.redirectionLimit = 1;
  904. channel.redirectTo(
  905. Services.io.newURI(result.redirectUrl, null, null)
  906. );
  907. return true;
  908. }*/
  909. return false;
  910. },
  911. observe: function(channel, topic) {
  912. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  913. return;
  914. }
  915. var URI = channel.URI;
  916. var channelData, result;
  917. if ( topic === 'http-on-examine-response' ) {
  918. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  919. return;
  920. }
  921. try {
  922. channelData = channel.getProperty(this.REQDATAKEY);
  923. } catch (ex) {
  924. return;
  925. }
  926. if ( !channelData ) {
  927. return;
  928. }
  929. if ( (1 << channelData[4] & this.VALID_CSP_TARGETS) === 0 ) {
  930. return;
  931. }
  932. topic = 'Content-Security-Policy';
  933. try {
  934. result = channel.getResponseHeader(topic);
  935. } catch (ex) {
  936. result = null;
  937. }
  938. result = vAPI.net.onHeadersReceived.callback({
  939. hostname: URI.asciiHost,
  940. parentFrameId: channelData[1],
  941. responseHeaders: result ? [{name: topic, value: result}] : [],
  942. tabId: channelData[3],
  943. url: URI.asciiSpec
  944. });
  945. if ( result ) {
  946. channel.setResponseHeader(
  947. topic,
  948. result.responseHeaders.pop().value,
  949. true
  950. );
  951. }
  952. return;
  953. }
  954. // http-on-opening-request
  955. var lastRequest = this.lastRequest[0];
  956. if ( lastRequest.url !== URI.spec ) {
  957. if ( this.lastRequest[1].url === URI.spec ) {
  958. lastRequest = this.lastRequest[1];
  959. } else {
  960. lastRequest.url = null;
  961. }
  962. }
  963. if ( lastRequest.url === null ) {
  964. lastRequest.type = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  965. result = this.handleRequest(channel, URI, {
  966. tabId: vAPI.noTabId,
  967. type: lastRequest.type
  968. });
  969. if ( result === true ) {
  970. return;
  971. }
  972. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  973. return;
  974. }
  975. // Carry data for behind-the-scene redirects
  976. channel.setProperty(
  977. this.REQDATAKEY,
  978. [lastRequest.type, vAPI.noTabId, null, 0, -1]
  979. );
  980. return;
  981. }
  982. // Important! When loading file via XHR for mirroring,
  983. // the URL will be the same, so it could fall into an infinite loop
  984. lastRequest.url = null;
  985. if ( this.handleRequest(channel, URI, lastRequest) ) {
  986. return;
  987. }
  988. if ( vAPI.fennec && lastRequest.type === this.MAIN_FRAME ) {
  989. vAPI.tabs.onNavigation({
  990. frameId: 0,
  991. tabId: lastRequest.tabId,
  992. url: URI.asciiSpec
  993. });
  994. }
  995. // If request is not handled we may use the data in on-modify-request
  996. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  997. channel.setProperty(this.REQDATAKEY, [
  998. lastRequest.frameId,
  999. lastRequest.parentFrameId,
  1000. lastRequest.sourceTabId,
  1001. lastRequest.tabId,
  1002. lastRequest.type
  1003. ]);
  1004. }
  1005. },
  1006. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1007. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1008. var result = this.ACCEPT;
  1009. // If error thrown, the redirect will fail
  1010. try {
  1011. var URI = newChannel.URI;
  1012. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1013. return;
  1014. }
  1015. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1016. return;
  1017. }
  1018. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1019. if ( this.handlePopup(URI, channelData[3], channelData[2]) ) {
  1020. result = this.ABORT;
  1021. return;
  1022. }
  1023. var details = {
  1024. frameId: channelData[0],
  1025. parentFrameId: channelData[1],
  1026. tabId: channelData[3],
  1027. type: channelData[4]
  1028. };
  1029. if ( this.handleRequest(newChannel, URI, details) ) {
  1030. result = this.ABORT;
  1031. return;
  1032. }
  1033. // Carry the data on in case of multiple redirects
  1034. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1035. newChannel.setProperty(this.REQDATAKEY, channelData);
  1036. }
  1037. } catch (ex) {
  1038. // console.error(ex);
  1039. } finally {
  1040. callback.onRedirectVerifyCallback(result);
  1041. }
  1042. }
  1043. };
  1044. /******************************************************************************/
  1045. vAPI.net = {};
  1046. /******************************************************************************/
  1047. vAPI.net.registerListeners = function() {
  1048. // Since it's not used
  1049. this.onBeforeSendHeaders = null;
  1050. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  1051. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1052. var shouldLoadListener = function(e) {
  1053. var details = e.data;
  1054. var tabId = vAPI.tabs.getTabId(e.target);
  1055. var sourceTabId = null;
  1056. // Popup candidate
  1057. if ( details.openerURL ) {
  1058. for ( var tab of vAPI.tabs.getAll() ) {
  1059. var URI = getBrowserForTab(tab).currentURI;
  1060. // Probably isn't the best method to identify the source tab
  1061. if ( URI.spec !== details.openerURL ) {
  1062. continue;
  1063. }
  1064. sourceTabId = vAPI.tabs.getTabId(tab);
  1065. if ( sourceTabId === tabId ) {
  1066. sourceTabId = null;
  1067. continue;
  1068. }
  1069. URI = Services.io.newURI(details.url, null, null);
  1070. if ( httpObserver.handlePopup(URI, tabId, sourceTabId) ) {
  1071. return;
  1072. }
  1073. break;
  1074. }
  1075. }
  1076. var lastRequest = httpObserver.lastRequest;
  1077. lastRequest[1] = lastRequest[0];
  1078. lastRequest[0] = {
  1079. frameId: details.frameId,
  1080. parentFrameId: details.parentFrameId,
  1081. sourceTabId: sourceTabId,
  1082. tabId: tabId,
  1083. type: details.type,
  1084. url: details.url
  1085. };
  1086. };
  1087. vAPI.messaging.globalMessageManager.addMessageListener(
  1088. shouldLoadListenerMessageName,
  1089. shouldLoadListener
  1090. );
  1091. httpObserver.register();
  1092. cleanupTasks.push(function() {
  1093. vAPI.messaging.globalMessageManager.removeMessageListener(
  1094. shouldLoadListenerMessageName,
  1095. shouldLoadListener
  1096. );
  1097. httpObserver.unregister();
  1098. });
  1099. };
  1100. /******************************************************************************/
  1101. vAPI.toolbarButton = {
  1102. id: location.host + '-button',
  1103. type: 'view',
  1104. viewId: location.host + '-panel',
  1105. label: vAPI.app.name,
  1106. tooltiptext: vAPI.app.name,
  1107. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1108. };
  1109. /******************************************************************************/
  1110. // Toolbar button UI for desktop Firefox
  1111. vAPI.toolbarButton.init = function() {
  1112. if ( vAPI.fennec ) {
  1113. // Menu UI for Fennec
  1114. var tb = {
  1115. menuItemIds: new WeakMap(),
  1116. label: vAPI.app.name,
  1117. tabs: {}
  1118. };
  1119. vAPI.toolbarButton = tb;
  1120. tb.getMenuItemLabel = function(tabId) {
  1121. var label = this.label;
  1122. if ( tabId === undefined ) {
  1123. return label;
  1124. }
  1125. var tabDetails = this.tabs[tabId];
  1126. if ( !tabDetails ) {
  1127. return label;
  1128. }
  1129. if ( !tabDetails.img ) {
  1130. label += ' (' + vAPI.i18n('fennecMenuItemBlockingOff') + ')';
  1131. } else if ( tabDetails.badge ) {
  1132. label += ' (' + tabDetails.badge + ')';
  1133. }
  1134. return label;
  1135. };
  1136. tb.onClick = function() {
  1137. var win = Services.wm.getMostRecentWindow('navigator:browser');
  1138. var curTabId = vAPI.tabs.getTabId(getTabBrowser(win).selectedTab);
  1139. vAPI.tabs.open({
  1140. url: 'popup.html?tabId=' + curTabId,
  1141. index: -1,
  1142. select: true
  1143. });
  1144. };
  1145. tb.updateState = function(win, tabId) {
  1146. var id = this.menuItemIds.get(win);
  1147. if ( !id ) {
  1148. return;
  1149. }
  1150. win.NativeWindow.menu.update(id, {
  1151. name: this.getMenuItemLabel(tabId)
  1152. });
  1153. };
  1154. // Only actually expecting one window under Fennec (note, not tabs, windows)
  1155. for ( var win of vAPI.tabs.getWindows() ) {
  1156. var label = tb.getMenuItemLabel();
  1157. var id = win.NativeWindow.menu.add({
  1158. name: label,
  1159. callback: tb.onClick
  1160. });
  1161. tb.menuItemIds.set(win, id);
  1162. }
  1163. cleanupTasks.push(function() {
  1164. for ( var win of vAPI.tabs.getWindows() ) {
  1165. var id = tb.menuItemIds.get(win);
  1166. if ( id ) {
  1167. win.NativeWindow.menu.remove(id);
  1168. tb.menuItemIds.delete(win);
  1169. }
  1170. }
  1171. });
  1172. return;
  1173. }
  1174. var CustomizableUI;
  1175. try {
  1176. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1177. } catch (ex) {
  1178. return;
  1179. }
  1180. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1181. this.styleURI = [
  1182. '#' + this.id + ' {',
  1183. 'list-style-image: url(',
  1184. vAPI.getURL('img/browsericons/icon16-off.svg'),
  1185. ');',
  1186. '}',
  1187. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1188. 'width: 160px;',
  1189. 'height: 290px;',
  1190. 'overflow: hidden !important;',
  1191. '}'
  1192. ];
  1193. var platformVersion = Services.appinfo.platformVersion;
  1194. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1195. this.styleURI.push(
  1196. '#' + this.id + '[badge]:not([badge=""])::after {',
  1197. 'position: absolute;',
  1198. 'margin-left: -16px;',
  1199. 'margin-top: 3px;',
  1200. 'padding: 1px 2px;',
  1201. 'font-size: 9px;',
  1202. 'font-weight: bold;',
  1203. 'color: #fff;',
  1204. 'background: #666;',
  1205. 'content: attr(badge);',
  1206. '}'
  1207. );
  1208. } else {
  1209. this.CUIEvents = {};
  1210. this.CUIEvents.updateBadge = function() {
  1211. var wId = vAPI.toolbarButton.id;
  1212. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1213. for ( var win of vAPI.tabs.getWindows() ) {
  1214. var button = win.document.getElementById(wId);
  1215. if ( buttonInPanel ) {
  1216. button.classList.remove('badged-button');
  1217. continue;
  1218. }
  1219. if ( button === null ) {
  1220. continue;
  1221. }
  1222. button.classList.add('badged-button');
  1223. }
  1224. if ( buttonInPanel ) {
  1225. return;
  1226. }
  1227. // Anonymous elements need some time to be reachable
  1228. setTimeout(this.updateBadgeStyle, 250);
  1229. };
  1230. this.CUIEvents.onCustomizeEnd = this.CUIEvents.updateBadge;
  1231. this.CUIEvents.onWidgetUnderflow = this.CUIEvents.updateBadge;
  1232. this.CUIEvents.updateBadgeStyle = function() {
  1233. var css = [
  1234. 'background: #666',
  1235. 'color: #fff'
  1236. ].join(';');
  1237. for ( var win of vAPI.tabs.getWindows() ) {
  1238. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1239. if ( button === null ) {
  1240. continue;
  1241. }
  1242. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1243. button,
  1244. 'class',
  1245. 'toolbarbutton-badge'
  1246. );
  1247. if ( !badge ) {
  1248. return;
  1249. }
  1250. badge.style.cssText = css;
  1251. }
  1252. };
  1253. this.onCreated = function(button) {
  1254. button.setAttribute('badge', '');
  1255. setTimeout(this.CUIEvents.updateBadge, 250);
  1256. };
  1257. CustomizableUI.addListener(this.CUIEvents);
  1258. }
  1259. this.styleURI = Services.io.newURI(
  1260. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1261. null,
  1262. null
  1263. );
  1264. this.closePopup = function({target}) {
  1265. CustomizableUI.hidePanelForNode(
  1266. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1267. );
  1268. };
  1269. CustomizableUI.createWidget(this);
  1270. vAPI.messaging.globalMessageManager.addMessageListener(
  1271. location.host + ':closePopup',
  1272. this.closePopup
  1273. );
  1274. cleanupTasks.push(function() {
  1275. if ( this.CUIEvents ) {
  1276. CustomizableUI.removeListener(this.CUIEvents);
  1277. }
  1278. CustomizableUI.destroyWidget(this.id);
  1279. vAPI.messaging.globalMessageManager.removeMessageListener(
  1280. location.host + ':closePopup',
  1281. this.closePopup
  1282. );
  1283. for ( var win of vAPI.tabs.getWindows() ) {
  1284. var panel = win.document.getElementById(this.viewId);
  1285. panel.parentNode.removeChild(panel);
  1286. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1287. .getInterface(Ci.nsIDOMWindowUtils)
  1288. .removeSheet(this.styleURI, 1);
  1289. }
  1290. }.bind(this));
  1291. this.init = null;
  1292. };
  1293. /******************************************************************************/
  1294. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1295. var panel = doc.createElement('panelview');
  1296. panel.setAttribute('id', this.viewId);
  1297. var iframe = doc.createElement('iframe');
  1298. iframe.setAttribute('type', 'content');
  1299. doc.getElementById('PanelUI-multiView')
  1300. .appendChild(panel)
  1301. .appendChild(iframe);
  1302. var updateTimer = null;
  1303. var delayedResize = function() {
  1304. if ( updateTimer ) {
  1305. return;
  1306. }
  1307. updateTimer = setTimeout(resizePopup, 10);
  1308. };
  1309. var resizePopup = function() {
  1310. updateTimer = null;
  1311. var body = iframe.contentDocument.body;
  1312. panel.parentNode.style.maxWidth = 'none';
  1313. // https://github.com/gorhill/uBlock/issues/730
  1314. // Voodoo programming: this recipe works
  1315. panel.style.height = iframe.style.height = body.clientHeight.toString() + 'px';
  1316. panel.style.width = iframe.style.width = body.clientWidth.toString() + 'px';
  1317. if ( iframe.clientHeight !== body.clientHeight || iframe.clientWidth !== body.clientWidth ) {
  1318. delayedResize();
  1319. }
  1320. };
  1321. var onPopupReady = function() {
  1322. var win = this.contentWindow;
  1323. if ( !win || win.location.host !== location.host ) {
  1324. return;
  1325. }
  1326. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1327. attributes: true,
  1328. characterData: true,
  1329. subtree: true
  1330. });
  1331. delayedResize();
  1332. };
  1333. iframe.addEventListener('load', onPopupReady, true);
  1334. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1335. .getInterface(Ci.nsIDOMWindowUtils)
  1336. .loadSheet(this.styleURI, 1);
  1337. };
  1338. /******************************************************************************/
  1339. vAPI.toolbarButton.onViewShowing = function({target}) {
  1340. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1341. };
  1342. /******************************************************************************/
  1343. vAPI.toolbarButton.onViewHiding = function({target}) {
  1344. target.parentNode.style.maxWidth = '';
  1345. target.firstChild.setAttribute('src', 'about:blank');
  1346. };
  1347. /******************************************************************************/
  1348. vAPI.toolbarButton.updateState = function(win, tabId) {
  1349. var button = win.document.getElementById(this.id);
  1350. if ( !button ) {
  1351. return;
  1352. }
  1353. var icon = this.tabs[tabId];
  1354. button.setAttribute('badge', icon && icon.badge || '');
  1355. if ( !icon || !icon.img ) {
  1356. icon = '';
  1357. }
  1358. else {
  1359. icon = 'url(' + vAPI.getURL('img/browsericons/icon16.svg') + ')';
  1360. }
  1361. button.style.listStyleImage = icon;
  1362. };
  1363. /******************************************************************************/
  1364. vAPI.toolbarButton.init();
  1365. /******************************************************************************/
  1366. vAPI.contextMenu = {
  1367. contextMap: {
  1368. frame: 'inFrame',
  1369. link: 'onLink',
  1370. image: 'onImage',
  1371. audio: 'onAudio',
  1372. video: 'onVideo',
  1373. editable: 'onEditableArea'
  1374. }
  1375. };
  1376. /******************************************************************************/
  1377. vAPI.contextMenu.displayMenuItem = function({target}) {
  1378. var doc = target.ownerDocument;
  1379. var gContextMenu = doc.defaultView.gContextMenu;
  1380. if ( !gContextMenu.browser ) {
  1381. return;
  1382. }
  1383. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1384. var currentURI = gContextMenu.browser.currentURI;
  1385. // https://github.com/gorhill/uBlock/issues/105
  1386. // TODO: Should the element picker works on any kind of pages?
  1387. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1388. menuitem.hidden = true;
  1389. return;
  1390. }
  1391. var ctx = vAPI.contextMenu.contexts;
  1392. if ( !ctx ) {
  1393. menuitem.hidden = false;
  1394. return;
  1395. }
  1396. var ctxMap = vAPI.contextMenu.contextMap;
  1397. for ( var context of ctx ) {
  1398. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1399. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1400. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1401. menuitem.hidden = false;
  1402. return;
  1403. }
  1404. if ( gContextMenu[ctxMap[context]] ) {
  1405. menuitem.hidden = false;
  1406. return;
  1407. }
  1408. }
  1409. menuitem.hidden = true;
  1410. };
  1411. /******************************************************************************/
  1412. vAPI.contextMenu.register = function(doc) {
  1413. if ( !this.menuItemId ) {
  1414. return;
  1415. }
  1416. if ( vAPI.fennec ) {
  1417. // TODO https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/NativeWindow/contextmenus/add
  1418. /*var nativeWindow = doc.defaultView.NativeWindow;
  1419. contextId = nativeWindow.contextmenus.add(
  1420. this.menuLabel,
  1421. nativeWindow.contextmenus.linkOpenableContext,
  1422. this.onCommand
  1423. );*/
  1424. return;
  1425. }
  1426. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1427. var menuitem = doc.createElement('menuitem');
  1428. menuitem.setAttribute('id', this.menuItemId);
  1429. menuitem.setAttribute('label', this.menuLabel);
  1430. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1431. menuitem.setAttribute('class', 'menuitem-iconic');
  1432. menuitem.addEventListener('command', this.onCommand);
  1433. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1434. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1435. };
  1436. /******************************************************************************/
  1437. vAPI.contextMenu.unregister = function(doc) {
  1438. if ( !this.menuItemId ) {
  1439. return;
  1440. }
  1441. if ( vAPI.fennec ) {
  1442. // TODO
  1443. return;
  1444. }
  1445. var menuitem = doc.getElementById(this.menuItemId);
  1446. var contextMenu = menuitem.parentNode;
  1447. menuitem.removeEventListener('command', this.onCommand);
  1448. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1449. contextMenu.removeChild(menuitem);
  1450. };
  1451. /******************************************************************************/
  1452. vAPI.contextMenu.create = function(details, callback) {
  1453. this.menuItemId = details.id;
  1454. this.menuLabel = details.title;
  1455. this.contexts = details.contexts;
  1456. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1457. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1458. } else {
  1459. // default in Chrome
  1460. this.contexts = ['page'];
  1461. }
  1462. this.onCommand = function() {
  1463. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1464. var details = {
  1465. menuItemId: this.id
  1466. };
  1467. if ( gContextMenu.inFrame ) {
  1468. details.tagName = 'iframe';
  1469. // Probably won't work with e10s
  1470. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1471. } else if ( gContextMenu.onImage ) {
  1472. details.tagName = 'img';
  1473. details.srcUrl = gContextMenu.mediaURL;
  1474. } else if ( gContextMenu.onAudio ) {
  1475. details.tagName = 'audio';
  1476. details.srcUrl = gContextMenu.mediaURL;
  1477. } else if ( gContextMenu.onVideo ) {
  1478. details.tagName = 'video';
  1479. details.srcUrl = gContextMenu.mediaURL;
  1480. } else if ( gContextMenu.onLink ) {
  1481. details.tagName = 'a';
  1482. details.linkUrl = gContextMenu.linkURL;
  1483. }
  1484. callback(details, {
  1485. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1486. url: gContextMenu.browser.currentURI.asciiSpec
  1487. });
  1488. };
  1489. for ( var win of vAPI.tabs.getWindows() ) {
  1490. this.register(win.document);
  1491. }
  1492. };
  1493. /******************************************************************************/
  1494. vAPI.contextMenu.remove = function() {
  1495. for ( var win of vAPI.tabs.getWindows() ) {
  1496. this.unregister(win.document);
  1497. }
  1498. this.menuItemId = null;
  1499. this.menuLabel = null;
  1500. this.contexts = null;
  1501. this.onCommand = null;
  1502. };
  1503. /******************************************************************************/
  1504. var optionsObserver = {
  1505. addonId: '{2b10c1c8-a11f-4bad-fe9c-1c11e82cac42}',
  1506. register: function() {
  1507. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1508. cleanupTasks.push(this.unregister.bind(this));
  1509. var browser = getBrowserForTab(vAPI.tabs.get(null));
  1510. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1511. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1512. }
  1513. },
  1514. unregister: function() {
  1515. Services.obs.removeObserver(this, 'addon-options-displayed');
  1516. },
  1517. setupOptionsButton: function(doc, id, page) {
  1518. var button = doc.getElementById(id);
  1519. if ( button === null ) {
  1520. return;
  1521. }
  1522. button.addEventListener('command', function() {
  1523. vAPI.tabs.open({ url: page, index: -1 });
  1524. });
  1525. button.label = vAPI.i18n(id);
  1526. },
  1527. observe: function(doc, topic, addonId) {
  1528. if ( addonId !== this.addonId ) {
  1529. return;
  1530. }
  1531. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1532. this.setupOptionsButton(doc, 'showNetworkLogButton', 'devtools.html');
  1533. }
  1534. };
  1535. optionsObserver.register();
  1536. /******************************************************************************/
  1537. vAPI.lastError = function() {
  1538. return null;
  1539. };
  1540. /******************************************************************************/
  1541. // This is called only once, when everything has been loaded in memory after
  1542. // the extension was launched. It can be used to inject content scripts
  1543. // in already opened web pages, to remove whatever nuisance could make it to
  1544. // the web pages before uBlock was ready.
  1545. vAPI.onLoadAllCompleted = function() {
  1546. var µb = µBlock;
  1547. for ( var tab of this.tabs.getAll() ) {
  1548. // We're insterested in only the tabs that were already loaded
  1549. if ( !vAPI.fennec && tab.hasAttribute('pending') ) {
  1550. continue;
  1551. }
  1552. var tabId = this.tabs.getTabId(tab);
  1553. var browser = getBrowserForTab(tab);
  1554. µb.bindTabToPageStats(tabId, browser.currentURI.asciiSpec);
  1555. browser.messageManager.sendAsyncMessage(
  1556. location.host + '-load-completed'
  1557. );
  1558. }
  1559. };
  1560. /******************************************************************************/
  1561. // Likelihood is that we do not have to punycode: given punycode overhead,
  1562. // it's faster to check and skip than do it unconditionally all the time.
  1563. var punycodeHostname = punycode.toASCII;
  1564. var isNotASCII = /[^\x21-\x7F]/;
  1565. vAPI.punycodeHostname = function(hostname) {
  1566. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1567. };
  1568. vAPI.punycodeURL = function(url) {
  1569. if ( isNotASCII.test(url) ) {
  1570. return Services.io.newURI(url, null, null).asciiSpec;
  1571. }
  1572. return url;
  1573. };
  1574. /******************************************************************************/
  1575. })();
  1576. /******************************************************************************/