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.

1929 lines
56 KiB

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