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.

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