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.

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