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.

1956 lines
57 KiB

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