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.

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