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.

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