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.

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