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.

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