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.

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