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.

1958 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. // Fixed by github.com/AlexVallat:
  47. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  48. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  49. var expectedNumberOfCleanups = 6;
  50. window.addEventListener('unload', function() {
  51. for ( var cleanup of cleanupTasks ) {
  52. cleanup();
  53. }
  54. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  55. console.error(
  56. 'uBlock> Cleanup tasks performed: %s (out of %s)',
  57. cleanupTasks.length,
  58. expectedNumberOfCleanups
  59. );
  60. }
  61. // frameModule needs to be cleared too
  62. var frameModule = {};
  63. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  64. frameModule.contentObserver.unregister();
  65. Cu.unload(vAPI.getURL('frameModule.js'));
  66. });
  67. /******************************************************************************/
  68. var SQLite = {
  69. open: function() {
  70. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  71. path.append('extension-data');
  72. if ( !path.exists() ) {
  73. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  74. }
  75. if ( !path.isDirectory() ) {
  76. throw Error('Should be a directory...');
  77. }
  78. path.append(location.host + '.sqlite');
  79. this.db = Services.storage.openDatabase(path);
  80. this.db.executeSimpleSQL(
  81. 'CREATE TABLE IF NOT EXISTS settings' +
  82. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  83. );
  84. cleanupTasks.push(function() {
  85. // VACUUM somewhere else, instead on unload?
  86. SQLite.run('VACUUM');
  87. SQLite.db.asyncClose();
  88. });
  89. },
  90. run: function(query, values, callback) {
  91. if ( !this.db ) {
  92. this.open();
  93. }
  94. var result = {};
  95. query = this.db.createAsyncStatement(query);
  96. if ( Array.isArray(values) && values.length ) {
  97. var i = values.length;
  98. while ( i-- ) {
  99. query.bindByIndex(i, values[i]);
  100. }
  101. }
  102. query.executeAsync({
  103. handleResult: function(rows) {
  104. if ( !rows || typeof callback !== 'function' ) {
  105. return;
  106. }
  107. var row;
  108. while ( row = rows.getNextRow() ) {
  109. // we assume that there will be two columns, since we're
  110. // using it only for preferences
  111. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  112. }
  113. },
  114. handleCompletion: function(reason) {
  115. if ( typeof callback === 'function' && reason === 0 ) {
  116. callback(result);
  117. }
  118. },
  119. handleError: function(error) {
  120. console.error('SQLite error ', error.result, error.message);
  121. }
  122. });
  123. }
  124. };
  125. /******************************************************************************/
  126. vAPI.storage = {
  127. QUOTA_BYTES: 100 * 1024 * 1024,
  128. sqlWhere: function(col, params) {
  129. if ( params > 0 ) {
  130. params = new Array(params + 1).join('?, ').slice(0, -2);
  131. return ' WHERE ' + col + ' IN (' + params + ')';
  132. }
  133. return '';
  134. },
  135. get: function(details, callback) {
  136. if ( typeof callback !== 'function' ) {
  137. return;
  138. }
  139. var values = [], defaults = false;
  140. if ( details !== null ) {
  141. if ( Array.isArray(details) ) {
  142. values = details;
  143. } else if ( typeof details === 'object' ) {
  144. defaults = true;
  145. values = Object.keys(details);
  146. } else {
  147. values = [details.toString()];
  148. }
  149. }
  150. SQLite.run(
  151. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  152. values,
  153. function(result) {
  154. var key;
  155. for ( key in result ) {
  156. result[key] = JSON.parse(result[key]);
  157. }
  158. if ( defaults ) {
  159. for ( key in details ) {
  160. if ( result[key] === undefined ) {
  161. result[key] = details[key];
  162. }
  163. }
  164. }
  165. callback(result);
  166. }
  167. );
  168. },
  169. set: function(details, callback) {
  170. var key, values = [], placeholders = [];
  171. for ( key in details ) {
  172. if ( !details.hasOwnProperty(key) ) {
  173. continue;
  174. }
  175. values.push(key);
  176. values.push(JSON.stringify(details[key]));
  177. placeholders.push('?, ?');
  178. }
  179. if ( !values.length ) {
  180. return;
  181. }
  182. SQLite.run(
  183. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  184. placeholders.join(' UNION SELECT '),
  185. values,
  186. callback
  187. );
  188. },
  189. remove: function(keys, callback) {
  190. if ( typeof keys === 'string' ) {
  191. keys = [keys];
  192. }
  193. SQLite.run(
  194. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  195. keys,
  196. callback
  197. );
  198. },
  199. clear: function(callback) {
  200. SQLite.run('DELETE FROM settings');
  201. SQLite.run('VACUUM', null, callback);
  202. },
  203. getBytesInUse: function(keys, callback) {
  204. if ( typeof callback !== 'function' ) {
  205. return;
  206. }
  207. SQLite.run(
  208. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  209. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  210. keys,
  211. function(result) {
  212. callback(result.size);
  213. }
  214. );
  215. }
  216. };
  217. /******************************************************************************/
  218. var windowWatcher = {
  219. onReady: function(e) {
  220. if ( e ) {
  221. this.removeEventListener(e.type, windowWatcher.onReady);
  222. }
  223. var wintype = this.document.documentElement.getAttribute('windowtype');
  224. if ( wintype !== 'navigator:browser' ) {
  225. return;
  226. }
  227. var tabContainer;
  228. var tabBrowser = getTabBrowser(this);
  229. if ( !tabBrowser ) {
  230. return;
  231. }
  232. if ( tabBrowser.deck ) {
  233. // Fennec
  234. tabContainer = tabBrowser.deck;
  235. } else if ( tabBrowser.tabContainer ) {
  236. // desktop Firefox
  237. tabContainer = tabBrowser.tabContainer;
  238. vAPI.contextMenu.register(this.document);
  239. } else {
  240. return;
  241. }
  242. tabContainer.addEventListener('TabClose', tabWatcher.onTabClose);
  243. tabContainer.addEventListener('TabSelect', tabWatcher.onTabSelect);
  244. // when new window is opened TabSelect doesn't run on the selected tab?
  245. },
  246. observe: function(win, topic) {
  247. if ( topic === 'domwindowopened' ) {
  248. win.addEventListener('DOMContentLoaded', this.onReady);
  249. }
  250. }
  251. };
  252. /******************************************************************************/
  253. var tabWatcher = {
  254. onTabClose: function({target}) {
  255. // target is tab in Firefox, browser in Fennec
  256. var tabId = vAPI.tabs.getTabId(target);
  257. vAPI.tabs.onClosed(tabId);
  258. delete vAPI.toolbarButton.tabs[tabId];
  259. },
  260. onTabSelect: function({target}) {
  261. vAPI.setIcon(vAPI.tabs.getTabId(target), getOwnerWindow(target));
  262. return;
  263. },
  264. };
  265. /******************************************************************************/
  266. vAPI.isBehindTheSceneTabId = function(tabId) {
  267. return tabId.toString() === '-1';
  268. };
  269. vAPI.noTabId = '-1';
  270. /******************************************************************************/
  271. var getTabBrowser = function(win) {
  272. return vAPI.fennec && win.BrowserApp || win.gBrowser || null;
  273. };
  274. /******************************************************************************/
  275. var getBrowserForTab = function(tab) {
  276. if ( !tab ) {
  277. return null;
  278. }
  279. return vAPI.fennec && tab.browser || tab.linkedBrowser || null;
  280. };
  281. /******************************************************************************/
  282. var getOwnerWindow = function(target) {
  283. if ( target.ownerDocument ) {
  284. return target.ownerDocument.defaultView;
  285. }
  286. // Fennec
  287. for ( var win of vAPI.tabs.getWindows() ) {
  288. for ( var tab of win.BrowserApp.tabs) {
  289. if ( tab === target || tab.window === target ) {
  290. return win;
  291. }
  292. }
  293. }
  294. return null;
  295. };
  296. /******************************************************************************/
  297. vAPI.tabs = {};
  298. /******************************************************************************/
  299. vAPI.tabs.registerListeners = function() {
  300. // onClosed - handled in tabWatcher.onTabClose
  301. // onPopup - handled in httpObserver.handlePopup
  302. for ( var win of this.getWindows() ) {
  303. windowWatcher.onReady.call(win);
  304. }
  305. Services.ww.registerNotification(windowWatcher);
  306. cleanupTasks.push(function() {
  307. Services.ww.unregisterNotification(windowWatcher);
  308. for ( var win of vAPI.tabs.getWindows() ) {
  309. vAPI.contextMenu.unregister(win.document);
  310. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  311. var tabContainer;
  312. var tabBrowser = getTabBrowser(win);
  313. if ( !tabBrowser ) {
  314. continue;
  315. }
  316. if ( tabBrowser.deck ) {
  317. // Fennec
  318. tabContainer = tabBrowser.deck;
  319. } else if ( tabBrowser.tabContainer ) {
  320. tabContainer = tabBrowser.tabContainer;
  321. tabBrowser.removeTabsProgressListener(tabWatcher);
  322. }
  323. tabContainer.removeEventListener('TabClose', tabWatcher.onTabClose);
  324. tabContainer.removeEventListener('TabSelect', tabWatcher.onTabSelect);
  325. // Close extension tabs
  326. for ( var tab of tabBrowser.tabs ) {
  327. var browser = getBrowserForTab(tab);
  328. if ( browser === null ) {
  329. continue;
  330. }
  331. var URI = browser.currentURI;
  332. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  333. vAPI.tabs._remove(tab, getTabBrowser(win));
  334. }
  335. }
  336. }
  337. });
  338. };
  339. /******************************************************************************/
  340. vAPI.tabs.stack = new WeakMap();
  341. vAPI.tabs.stackId = 1;
  342. /******************************************************************************/
  343. vAPI.tabs.getTabId = function(target) {
  344. if ( !target ) {
  345. return vAPI.noTabId;
  346. }
  347. if ( vAPI.fennec ) {
  348. if ( target.browser ) {
  349. // target is a tab
  350. target = target.browser;
  351. }
  352. } else if ( target.linkedPanel ) {
  353. // target is a tab
  354. target = target.linkedBrowser;
  355. }
  356. if ( target.localName !== 'browser' ) {
  357. return vAPI.noTabId;
  358. }
  359. var tabId = this.stack.get(target);
  360. if ( !tabId ) {
  361. tabId = '' + this.stackId++;
  362. this.stack.set(target, tabId);
  363. }
  364. return tabId;
  365. };
  366. /******************************************************************************/
  367. // If tabIds is an array, then an array of tabs will be returned,
  368. // otherwise a single tab
  369. vAPI.tabs.getTabsForIds = function(tabIds) {
  370. var tabs = [];
  371. var singleTab = !Array.isArray(tabIds);
  372. if ( singleTab ) {
  373. tabIds = [tabIds];
  374. }
  375. for ( var tab of this.getAll() ) {
  376. var tabId = this.stack.get(getBrowserForTab(tab));
  377. if ( !tabId ) {
  378. continue;
  379. }
  380. if ( tabIds.indexOf(tabId) !== -1 ) {
  381. tabs.push(tab);
  382. }
  383. if ( tabs.length >= tabIds.length ) {
  384. break;
  385. }
  386. }
  387. return singleTab ? tabs[0] || null : tabs;
  388. };
  389. /******************************************************************************/
  390. vAPI.tabs.get = function(tabId, callback) {
  391. var tab, win;
  392. if ( tabId === null ) {
  393. win = Services.wm.getMostRecentWindow('navigator:browser');
  394. tab = getTabBrowser(win).selectedTab;
  395. tabId = this.getTabId(tab);
  396. } else {
  397. tab = this.getTabsForIds(tabId);
  398. if ( tab ) {
  399. win = getOwnerWindow(tab);
  400. }
  401. }
  402. // For internal use
  403. if ( typeof callback !== 'function' ) {
  404. return tab;
  405. }
  406. if ( !tab ) {
  407. callback();
  408. return;
  409. }
  410. var windows = this.getWindows();
  411. var browser = getBrowserForTab(tab);
  412. var tabBrowser = getTabBrowser(win);
  413. var tabIndex, tabTitle;
  414. if ( vAPI.fennec ) {
  415. tabIndex = tabBrowser.tabs.indexOf(tab);
  416. tabTitle = browser.contentTitle;
  417. } else {
  418. tabIndex = tabBrowser.browsers.indexOf(browser);
  419. tabTitle = tab.label;
  420. }
  421. callback({
  422. id: tabId,
  423. index: tabIndex,
  424. windowId: windows.indexOf(win),
  425. active: tab === tabBrowser.selectedTab,
  426. url: browser.currentURI.asciiSpec,
  427. title: tabTitle
  428. });
  429. };
  430. /******************************************************************************/
  431. vAPI.tabs.getAll = function(window) {
  432. var win, tab;
  433. var tabs = [];
  434. for ( win of this.getWindows() ) {
  435. if ( window && window !== win ) {
  436. continue;
  437. }
  438. var tabBrowser = getTabBrowser(win);
  439. if ( tabBrowser === null ) {
  440. continue;
  441. }
  442. for ( tab of tabBrowser.tabs ) {
  443. tabs.push(tab);
  444. }
  445. }
  446. return tabs;
  447. };
  448. /******************************************************************************/
  449. vAPI.tabs.getWindows = function() {
  450. var winumerator = Services.wm.getEnumerator('navigator:browser');
  451. var windows = [];
  452. while ( winumerator.hasMoreElements() ) {
  453. var win = winumerator.getNext();
  454. if ( !win.closed ) {
  455. windows.push(win);
  456. }
  457. }
  458. return windows;
  459. };
  460. /******************************************************************************/
  461. // properties of the details object:
  462. // url: 'URL', // the address that will be opened
  463. // tabId: 1, // the tab is used if set, instead of creating a new one
  464. // index: -1, // undefined: end of the list, -1: following tab, or after index
  465. // active: false, // opens the tab in background - true and undefined: foreground
  466. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  467. vAPI.tabs.open = function(details) {
  468. if ( !details.url ) {
  469. return null;
  470. }
  471. // extension pages
  472. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  473. details.url = vAPI.getURL(details.url);
  474. }
  475. var win, tab, tabBrowser;
  476. if ( details.select ) {
  477. var URI = Services.io.newURI(details.url, null, null);
  478. for ( tab of this.getAll() ) {
  479. var browser = getBrowserForTab(tab);
  480. // Or simply .equals if we care about the fragment
  481. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  482. continue;
  483. }
  484. this.select(tab);
  485. return;
  486. }
  487. }
  488. if ( details.active === undefined ) {
  489. details.active = true;
  490. }
  491. if ( details.tabId ) {
  492. tab = this.getTabsForIds(details.tabId);
  493. if ( tab ) {
  494. getBrowserForTab(tab).loadURI(details.url);
  495. return;
  496. }
  497. }
  498. win = Services.wm.getMostRecentWindow('navigator:browser');
  499. tabBrowser = getTabBrowser(win);
  500. if ( vAPI.fennec ) {
  501. tabBrowser.addTab(details.url, {selected: details.active !== false});
  502. // Note that it's impossible to move tabs on Fennec, so don't bother
  503. return;
  504. }
  505. if ( details.index === -1 ) {
  506. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  507. }
  508. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  509. if ( details.index !== undefined ) {
  510. tabBrowser.moveTabTo(tab, details.index);
  511. }
  512. };
  513. /******************************************************************************/
  514. // Replace the URL of a tab. Noop if the tab does not exist.
  515. vAPI.tabs.replace = function(tabId, url) {
  516. var targetURL = url;
  517. // extension pages
  518. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  519. targetURL = vAPI.getURL(targetURL);
  520. }
  521. var tab = this.getTabsForIds(tabId);
  522. if ( tab ) {
  523. getBrowserForTab(tab).loadURI(targetURL);
  524. }
  525. };
  526. /******************************************************************************/
  527. vAPI.tabs._remove = function(tab, tabBrowser) {
  528. if ( vAPI.fennec ) {
  529. tabBrowser.closeTab(tab);
  530. return;
  531. }
  532. tabBrowser.removeTab(tab);
  533. };
  534. /******************************************************************************/
  535. vAPI.tabs.remove = function(tabIds) {
  536. if ( !Array.isArray(tabIds) ) {
  537. tabIds = [tabIds];
  538. }
  539. var tabs = this.getTabsForIds(tabIds);
  540. if ( tabs.length === 0 ) {
  541. return;
  542. }
  543. for ( var tab of tabs ) {
  544. this._remove(tab, getTabBrowser(getOwnerWindow(tab)));
  545. }
  546. };
  547. /******************************************************************************/
  548. vAPI.tabs.reload = function(tabId) {
  549. var tab = this.get(tabId);
  550. if ( !tab ) {
  551. return;
  552. }
  553. getBrowserForTab(tab).webNavigation.reload(
  554. Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE
  555. );
  556. };
  557. /******************************************************************************/
  558. vAPI.tabs.select = function(tab) {
  559. tab = typeof tab === 'object' ? tab : this.get(tab);
  560. if ( !tab ) {
  561. return;
  562. }
  563. var tabBrowser = getTabBrowser(getOwnerWindow(tab));
  564. if ( vAPI.fennec ) {
  565. tabBrowser.selectTab(tab);
  566. } else {
  567. tabBrowser.selectedTab = tab;
  568. }
  569. };
  570. /******************************************************************************/
  571. vAPI.tabs.injectScript = function(tabId, details, callback) {
  572. var tab = this.get(tabId);
  573. if ( !tab ) {
  574. return;
  575. }
  576. if ( typeof details.file !== 'string' ) {
  577. return;
  578. }
  579. details.file = vAPI.getURL(details.file);
  580. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  581. location.host + ':broadcast',
  582. JSON.stringify({
  583. broadcast: true,
  584. channelName: 'vAPI',
  585. msg: {
  586. cmd: 'injectScript',
  587. details: details
  588. }
  589. })
  590. );
  591. if ( typeof callback === 'function' ) {
  592. setTimeout(callback, 13);
  593. }
  594. };
  595. /******************************************************************************/
  596. vAPI.setIcon = function(tabId, iconStatus, badge) {
  597. // If badge is undefined, then setIcon was called from the TabSelect event
  598. var win = badge === undefined
  599. ? iconStatus
  600. : Services.wm.getMostRecentWindow('navigator:browser');
  601. var curTabId = vAPI.tabs.getTabId(getTabBrowser(win).selectedTab);
  602. var tb = vAPI.toolbarButton;
  603. // from 'TabSelect' event
  604. if ( tabId === undefined ) {
  605. tabId = curTabId;
  606. } else if ( badge !== undefined ) {
  607. tb.tabs[tabId] = { badge: badge, img: iconStatus === 'on' };
  608. }
  609. if ( tabId === curTabId ) {
  610. tb.updateState(win, tabId);
  611. }
  612. };
  613. /******************************************************************************/
  614. vAPI.messaging = {
  615. get globalMessageManager() {
  616. return Cc['@mozilla.org/globalmessagemanager;1']
  617. .getService(Ci.nsIMessageListenerManager);
  618. },
  619. frameScript: vAPI.getURL('frameScript.js'),
  620. listeners: {},
  621. defaultHandler: null,
  622. NOOPFUNC: function(){},
  623. UNHANDLED: 'vAPI.messaging.notHandled'
  624. };
  625. /******************************************************************************/
  626. vAPI.messaging.listen = function(listenerName, callback) {
  627. this.listeners[listenerName] = callback;
  628. };
  629. /******************************************************************************/
  630. vAPI.messaging.onMessage = function({target, data}) {
  631. var messageManager = target.messageManager;
  632. if ( !messageManager ) {
  633. // Message came from a popup, and its message manager is not usable.
  634. // So instead we broadcast to the parent window.
  635. messageManager = getOwnerWindow(
  636. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  637. ).messageManager;
  638. }
  639. var channelNameRaw = data.channelName;
  640. var pos = channelNameRaw.indexOf('|');
  641. var channelName = channelNameRaw.slice(pos + 1);
  642. var callback = vAPI.messaging.NOOPFUNC;
  643. if ( data.requestId !== undefined ) {
  644. callback = CallbackWrapper.factory(
  645. messageManager,
  646. channelName,
  647. channelNameRaw.slice(0, pos),
  648. data.requestId
  649. ).callback;
  650. }
  651. var sender = {
  652. tab: {
  653. id: vAPI.tabs.getTabId(target)
  654. }
  655. };
  656. // Specific handler
  657. var r = vAPI.messaging.UNHANDLED;
  658. var listener = vAPI.messaging.listeners[channelName];
  659. if ( typeof listener === 'function' ) {
  660. r = listener(data.msg, sender, callback);
  661. }
  662. if ( r !== vAPI.messaging.UNHANDLED ) {
  663. return;
  664. }
  665. // Default handler
  666. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  667. if ( r !== vAPI.messaging.UNHANDLED ) {
  668. return;
  669. }
  670. console.error('uBlock> messaging > unknown request: %o', data);
  671. // Unhandled:
  672. // Need to callback anyways in case caller expected an answer, or
  673. // else there is a memory leak on caller's side
  674. callback();
  675. };
  676. /******************************************************************************/
  677. vAPI.messaging.setup = function(defaultHandler) {
  678. // Already setup?
  679. if ( this.defaultHandler !== null ) {
  680. return;
  681. }
  682. if ( typeof defaultHandler !== 'function' ) {
  683. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  684. }
  685. this.defaultHandler = defaultHandler;
  686. this.globalMessageManager.addMessageListener(
  687. location.host + ':background',
  688. this.onMessage
  689. );
  690. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  691. cleanupTasks.push(function() {
  692. var gmm = vAPI.messaging.globalMessageManager;
  693. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  694. gmm.removeMessageListener(
  695. location.host + ':background',
  696. vAPI.messaging.onMessage
  697. );
  698. });
  699. };
  700. /******************************************************************************/
  701. vAPI.messaging.broadcast = function(message) {
  702. this.globalMessageManager.broadcastAsyncMessage(
  703. location.host + ':broadcast',
  704. JSON.stringify({broadcast: true, msg: message})
  705. );
  706. };
  707. /******************************************************************************/
  708. // This allows to avoid creating a closure for every single message which
  709. // expects an answer. Having a closure created each time a message is processed
  710. // has been always bothering me. Another benefit of the implementation here
  711. // is to reuse the callback proxy object, so less memory churning.
  712. //
  713. // https://developers.google.com/speed/articles/optimizing-javascript
  714. // "Creating a closure is significantly slower then creating an inner
  715. // function without a closure, and much slower than reusing a static
  716. // function"
  717. //
  718. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  719. // "the dreaded 'uniformly slow code' case where every function takes 1%
  720. // of CPU and you have to make one hundred separate performance optimizations
  721. // to improve performance at all"
  722. //
  723. // http://jsperf.com/closure-no-closure/2
  724. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  725. this.callback = this.proxy.bind(this); // bind once
  726. this.init(messageManager, channelName, listenerId, requestId);
  727. };
  728. CallbackWrapper.junkyard = [];
  729. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  730. var wrapper = CallbackWrapper.junkyard.pop();
  731. if ( wrapper ) {
  732. wrapper.init(messageManager, channelName, listenerId, requestId);
  733. return wrapper;
  734. }
  735. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  736. };
  737. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  738. this.messageManager = messageManager;
  739. this.channelName = channelName;
  740. this.listenerId = listenerId;
  741. this.requestId = requestId;
  742. };
  743. CallbackWrapper.prototype.proxy = function(response) {
  744. var message = JSON.stringify({
  745. requestId: this.requestId,
  746. channelName: this.channelName,
  747. msg: response !== undefined ? response : null
  748. });
  749. if ( this.messageManager.sendAsyncMessage ) {
  750. this.messageManager.sendAsyncMessage(this.listenerId, message);
  751. } else {
  752. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  753. }
  754. // Mark for reuse
  755. this.messageManager =
  756. this.channelName =
  757. this.requestId =
  758. this.listenerId = null;
  759. CallbackWrapper.junkyard.push(this);
  760. };
  761. /******************************************************************************/
  762. var httpObserver = {
  763. classDescription: 'net-channel-event-sinks for ' + location.host,
  764. classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  765. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  766. REQDATAKEY: location.host + 'reqdata',
  767. ABORT: Components.results.NS_BINDING_ABORTED,
  768. ACCEPT: Components.results.NS_SUCCEEDED,
  769. // Request types: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  770. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  771. VALID_CSP_TARGETS: 1 << Ci.nsIContentPolicy.TYPE_DOCUMENT |
  772. 1 << Ci.nsIContentPolicy.TYPE_SUBDOCUMENT,
  773. typeMap: {
  774. 1: 'other',
  775. 2: 'script',
  776. 3: 'image',
  777. 4: 'stylesheet',
  778. 5: 'object',
  779. 6: 'main_frame',
  780. 7: 'sub_frame',
  781. 11: 'xmlhttprequest',
  782. 12: 'object',
  783. 14: 'font',
  784. 21: 'image'
  785. },
  786. lastRequest: [{}, {}],
  787. get componentRegistrar() {
  788. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  789. },
  790. get categoryManager() {
  791. return Cc['@mozilla.org/categorymanager;1']
  792. .getService(Ci.nsICategoryManager);
  793. },
  794. QueryInterface: (function() {
  795. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  796. return XPCOMUtils.generateQI([
  797. Ci.nsIFactory,
  798. Ci.nsIObserver,
  799. Ci.nsIChannelEventSink,
  800. Ci.nsISupportsWeakReference
  801. ]);
  802. })(),
  803. createInstance: function(outer, iid) {
  804. if ( outer ) {
  805. throw Components.results.NS_ERROR_NO_AGGREGATION;
  806. }
  807. return this.QueryInterface(iid);
  808. },
  809. register: function() {
  810. Services.obs.addObserver(this, 'http-on-opening-request', true);
  811. Services.obs.addObserver(this, 'http-on-examine-response', true);
  812. // Guard against stale instances not having been unregistered
  813. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  814. try {
  815. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  816. } catch (ex) {
  817. console.error('uBlock> httpObserver > unable to unregister stale instance: ', ex);
  818. }
  819. }
  820. this.componentRegistrar.registerFactory(
  821. this.classID,
  822. this.classDescription,
  823. this.contractID,
  824. this
  825. );
  826. this.categoryManager.addCategoryEntry(
  827. 'net-channel-event-sinks',
  828. this.contractID,
  829. this.contractID,
  830. false,
  831. true
  832. );
  833. },
  834. unregister: function() {
  835. Services.obs.removeObserver(this, 'http-on-opening-request');
  836. Services.obs.removeObserver(this, 'http-on-examine-response');
  837. this.componentRegistrar.unregisterFactory(this.classID, this);
  838. this.categoryManager.deleteCategoryEntry(
  839. 'net-channel-event-sinks',
  840. this.contractID,
  841. false
  842. );
  843. },
  844. handlePopup: function(URI, tabId, sourceTabId) {
  845. if ( !sourceTabId ) {
  846. return false;
  847. }
  848. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  849. return false;
  850. }
  851. var result = vAPI.tabs.onPopup({
  852. targetTabId: tabId,
  853. openerTabId: sourceTabId,
  854. targetURL: URI.asciiSpec
  855. });
  856. return result === true;
  857. },
  858. handleRequest: function(channel, URI, details) {
  859. var onBeforeRequest = vAPI.net.onBeforeRequest;
  860. var type = this.typeMap[details.type] || 'other';
  861. if ( onBeforeRequest.types.has(type) === false ) {
  862. return false;
  863. }
  864. var result = onBeforeRequest.callback({
  865. frameId: details.frameId,
  866. hostname: URI.asciiHost,
  867. parentFrameId: details.parentFrameId,
  868. tabId: details.tabId,
  869. type: type,
  870. url: URI.asciiSpec
  871. });
  872. if ( !result || typeof result !== 'object' ) {
  873. return false;
  874. }
  875. if ( result.cancel === true ) {
  876. channel.cancel(this.ABORT);
  877. return true;
  878. }
  879. /*if ( result.redirectUrl ) {
  880. channel.redirectionLimit = 1;
  881. channel.redirectTo(
  882. Services.io.newURI(result.redirectUrl, null, null)
  883. );
  884. return true;
  885. }*/
  886. return false;
  887. },
  888. observe: function(channel, topic) {
  889. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  890. return;
  891. }
  892. var URI = channel.URI;
  893. var channelData, result;
  894. if ( topic === 'http-on-examine-response' ) {
  895. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  896. return;
  897. }
  898. try {
  899. channelData = channel.getProperty(this.REQDATAKEY);
  900. } catch (ex) {
  901. return;
  902. }
  903. if ( !channelData ) {
  904. return;
  905. }
  906. if ( (1 << channelData[4] & this.VALID_CSP_TARGETS) === 0 ) {
  907. return;
  908. }
  909. topic = 'Content-Security-Policy';
  910. try {
  911. result = channel.getResponseHeader(topic);
  912. } catch (ex) {
  913. result = null;
  914. }
  915. result = vAPI.net.onHeadersReceived.callback({
  916. hostname: URI.asciiHost,
  917. parentFrameId: channelData[1],
  918. responseHeaders: result ? [{name: topic, value: result}] : [],
  919. tabId: channelData[3],
  920. url: URI.asciiSpec
  921. });
  922. if ( result ) {
  923. channel.setResponseHeader(
  924. topic,
  925. result.responseHeaders.pop().value,
  926. true
  927. );
  928. }
  929. return;
  930. }
  931. // http-on-opening-request
  932. var lastRequest = this.lastRequest[0];
  933. if ( lastRequest.url !== URI.spec ) {
  934. if ( this.lastRequest[1].url === URI.spec ) {
  935. lastRequest = this.lastRequest[1];
  936. } else {
  937. lastRequest.url = null;
  938. }
  939. }
  940. if ( lastRequest.url === null ) {
  941. lastRequest.type = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  942. result = this.handleRequest(channel, URI, {
  943. tabId: vAPI.noTabId,
  944. type: lastRequest.type
  945. });
  946. if ( result === true ) {
  947. return;
  948. }
  949. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  950. return;
  951. }
  952. // Carry data for behind-the-scene redirects
  953. channel.setProperty(
  954. this.REQDATAKEY,
  955. [lastRequest.type, vAPI.noTabId, null, 0, -1]
  956. );
  957. return;
  958. }
  959. // Important! When loading file via XHR for mirroring,
  960. // the URL will be the same, so it could fall into an infinite loop
  961. lastRequest.url = null;
  962. if ( this.handleRequest(channel, URI, lastRequest) ) {
  963. return;
  964. }
  965. // If request is not handled we may use the data in on-modify-request
  966. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  967. channel.setProperty(this.REQDATAKEY, [
  968. lastRequest.frameId,
  969. lastRequest.parentFrameId,
  970. lastRequest.sourceTabId,
  971. lastRequest.tabId,
  972. lastRequest.type
  973. ]);
  974. }
  975. },
  976. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  977. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  978. var result = this.ACCEPT;
  979. // If error thrown, the redirect will fail
  980. try {
  981. var URI = newChannel.URI;
  982. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  983. return;
  984. }
  985. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  986. return;
  987. }
  988. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  989. if ( this.handlePopup(URI, channelData[3], channelData[2]) ) {
  990. result = this.ABORT;
  991. return;
  992. }
  993. var details = {
  994. frameId: channelData[0],
  995. parentFrameId: channelData[1],
  996. tabId: channelData[3],
  997. type: channelData[4]
  998. };
  999. if ( this.handleRequest(newChannel, URI, details) ) {
  1000. result = this.ABORT;
  1001. return;
  1002. }
  1003. // Carry the data on in case of multiple redirects
  1004. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1005. newChannel.setProperty(this.REQDATAKEY, channelData);
  1006. }
  1007. } catch (ex) {
  1008. // console.error(ex);
  1009. } finally {
  1010. callback.onRedirectVerifyCallback(result);
  1011. }
  1012. }
  1013. };
  1014. /******************************************************************************/
  1015. vAPI.net = {};
  1016. /******************************************************************************/
  1017. vAPI.net.registerListeners = function() {
  1018. // Since it's not used
  1019. this.onBeforeSendHeaders = null;
  1020. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  1021. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1022. var shouldLoadListener = function(e) {
  1023. var details = e.data;
  1024. var tabId = vAPI.tabs.getTabId(e.target);
  1025. var sourceTabId = null;
  1026. // Popup candidate
  1027. if ( details.openerURL ) {
  1028. for ( var tab of vAPI.tabs.getAll() ) {
  1029. var URI = getBrowserForTab(tab).currentURI;
  1030. // Probably isn't the best method to identify the source tab
  1031. if ( URI.spec !== details.openerURL ) {
  1032. continue;
  1033. }
  1034. sourceTabId = vAPI.tabs.getTabId(tab);
  1035. if ( sourceTabId === tabId ) {
  1036. sourceTabId = null;
  1037. continue;
  1038. }
  1039. URI = Services.io.newURI(details.url, null, null);
  1040. if ( httpObserver.handlePopup(URI, tabId, sourceTabId) ) {
  1041. return;
  1042. }
  1043. break;
  1044. }
  1045. }
  1046. var lastRequest = httpObserver.lastRequest;
  1047. lastRequest[1] = lastRequest[0];
  1048. lastRequest[0] = {
  1049. frameId: details.frameId,
  1050. parentFrameId: details.parentFrameId,
  1051. sourceTabId: sourceTabId,
  1052. tabId: tabId,
  1053. type: details.type,
  1054. url: details.url
  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: 'uBlock0@raymondhill.net',
  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.tabContextManager.commit(tabId, browser.currentURI.asciiSpec);
  1556. µb.bindTabToPageStats(tabId, browser.currentURI.asciiSpec);
  1557. browser.messageManager.sendAsyncMessage(
  1558. location.host + '-load-completed'
  1559. );
  1560. }
  1561. };
  1562. /******************************************************************************/
  1563. // Likelihood is that we do not have to punycode: given punycode overhead,
  1564. // it's faster to check and skip than do it unconditionally all the time.
  1565. var punycodeHostname = punycode.toASCII;
  1566. var isNotASCII = /[^\x21-\x7F]/;
  1567. vAPI.punycodeHostname = function(hostname) {
  1568. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1569. };
  1570. vAPI.punycodeURL = function(url) {
  1571. if ( isNotASCII.test(url) ) {
  1572. return Services.io.newURI(url, null, null).asciiSpec;
  1573. }
  1574. return url;
  1575. };
  1576. /******************************************************************************/
  1577. })();
  1578. /******************************************************************************/