You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1976 lines
58 KiB

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