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.

1797 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, getTabBrowser(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. getBrowserForTab(tab).webNavigation.reload(0);
  575. };
  576. /******************************************************************************/
  577. vAPI.tabs.injectScript = function(tabId, details, callback) {
  578. var tab = this.get(tabId);
  579. if ( !tab ) {
  580. return;
  581. }
  582. if ( typeof details.file !== 'string' ) {
  583. return;
  584. }
  585. details.file = vAPI.getURL(details.file);
  586. tab.linkedBrowser.messageManager.sendAsyncMessage(
  587. location.host + ':broadcast',
  588. JSON.stringify({
  589. broadcast: true,
  590. channelName: 'vAPI',
  591. msg: {
  592. cmd: 'injectScript',
  593. details: details
  594. }
  595. })
  596. );
  597. if ( typeof callback === 'function' ) {
  598. setTimeout(callback, 13);
  599. }
  600. };
  601. /******************************************************************************/
  602. vAPI.setIcon = function(tabId, iconStatus, badge) {
  603. // If badge is undefined, then setIcon was called from the TabSelect event
  604. var win = badge === undefined
  605. ? iconStatus
  606. : Services.wm.getMostRecentWindow('navigator:browser');
  607. var curTabId = vAPI.tabs.getTabId(getTabBrowser(win).selectedTab);
  608. var tb = vAPI.toolbarButton;
  609. // from 'TabSelect' event
  610. if ( tabId === undefined ) {
  611. tabId = curTabId;
  612. } else if ( badge !== undefined ) {
  613. tb.tabs[tabId] = { badge: badge, img: iconStatus === 'on' };
  614. }
  615. if ( tabId !== curTabId ) {
  616. return;
  617. }
  618. var button = win.document.getElementById(tb.id);
  619. if ( !button ) {
  620. return;
  621. }
  622. var icon = tb.tabs[tabId];
  623. button.setAttribute('badge', icon && icon.badge || '');
  624. if ( !icon || !icon.img ) {
  625. icon = '';
  626. }
  627. else {
  628. icon = 'url(' + vAPI.getURL('img/browsericons/icon16.svg') + ')';
  629. }
  630. button.style.listStyleImage = icon;
  631. };
  632. /******************************************************************************/
  633. vAPI.messaging = {
  634. get globalMessageManager() {
  635. return Cc['@mozilla.org/globalmessagemanager;1']
  636. .getService(Ci.nsIMessageListenerManager);
  637. },
  638. frameScript: vAPI.getURL('frameScript.js'),
  639. listeners: {},
  640. defaultHandler: null,
  641. NOOPFUNC: function(){},
  642. UNHANDLED: 'vAPI.messaging.notHandled'
  643. };
  644. /******************************************************************************/
  645. vAPI.messaging.listen = function(listenerName, callback) {
  646. this.listeners[listenerName] = callback;
  647. };
  648. /******************************************************************************/
  649. vAPI.messaging.onMessage = function({target, data}) {
  650. var messageManager = target.messageManager;
  651. if ( !messageManager ) {
  652. // Message came from a popup, and its message manager is not usable.
  653. // So instead we broadcast to the parent window.
  654. messageManager = getOwnerWindow(
  655. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  656. ).messageManager;
  657. }
  658. var channelNameRaw = data.channelName;
  659. var pos = channelNameRaw.indexOf('|');
  660. var channelName = channelNameRaw.slice(pos + 1);
  661. var callback = vAPI.messaging.NOOPFUNC;
  662. if ( data.requestId !== undefined ) {
  663. callback = CallbackWrapper.factory(
  664. messageManager,
  665. channelName,
  666. channelNameRaw.slice(0, pos),
  667. data.requestId
  668. ).callback;
  669. }
  670. var sender = {
  671. tab: {
  672. id: vAPI.tabs.getTabId(target)
  673. }
  674. };
  675. // Specific handler
  676. var r = vAPI.messaging.UNHANDLED;
  677. var listener = vAPI.messaging.listeners[channelName];
  678. if ( typeof listener === 'function' ) {
  679. r = listener(data.msg, sender, callback);
  680. }
  681. if ( r !== vAPI.messaging.UNHANDLED ) {
  682. return;
  683. }
  684. // Default handler
  685. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  686. if ( r !== vAPI.messaging.UNHANDLED ) {
  687. return;
  688. }
  689. console.error('µBlock> messaging > unknown request: %o', data);
  690. // Unhandled:
  691. // Need to callback anyways in case caller expected an answer, or
  692. // else there is a memory leak on caller's side
  693. callback();
  694. };
  695. /******************************************************************************/
  696. vAPI.messaging.setup = function(defaultHandler) {
  697. // Already setup?
  698. if ( this.defaultHandler !== null ) {
  699. return;
  700. }
  701. if ( typeof defaultHandler !== 'function' ) {
  702. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  703. }
  704. this.defaultHandler = defaultHandler;
  705. this.globalMessageManager.addMessageListener(
  706. location.host + ':background',
  707. this.onMessage
  708. );
  709. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  710. cleanupTasks.push(function() {
  711. var gmm = vAPI.messaging.globalMessageManager;
  712. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  713. gmm.removeMessageListener(
  714. location.host + ':background',
  715. vAPI.messaging.onMessage
  716. );
  717. });
  718. };
  719. /******************************************************************************/
  720. vAPI.messaging.broadcast = function(message) {
  721. this.globalMessageManager.broadcastAsyncMessage(
  722. location.host + ':broadcast',
  723. JSON.stringify({broadcast: true, msg: message})
  724. );
  725. };
  726. /******************************************************************************/
  727. // This allows to avoid creating a closure for every single message which
  728. // expects an answer. Having a closure created each time a message is processed
  729. // has been always bothering me. Another benefit of the implementation here
  730. // is to reuse the callback proxy object, so less memory churning.
  731. //
  732. // https://developers.google.com/speed/articles/optimizing-javascript
  733. // "Creating a closure is significantly slower then creating an inner
  734. // function without a closure, and much slower than reusing a static
  735. // function"
  736. //
  737. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  738. // "the dreaded 'uniformly slow code' case where every function takes 1%
  739. // of CPU and you have to make one hundred separate performance optimizations
  740. // to improve performance at all"
  741. //
  742. // http://jsperf.com/closure-no-closure/2
  743. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  744. this.callback = this.proxy.bind(this); // bind once
  745. this.init(messageManager, channelName, listenerId, requestId);
  746. };
  747. CallbackWrapper.junkyard = [];
  748. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  749. var wrapper = CallbackWrapper.junkyard.pop();
  750. if ( wrapper ) {
  751. wrapper.init(messageManager, channelName, listenerId, requestId);
  752. return wrapper;
  753. }
  754. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  755. };
  756. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  757. this.messageManager = messageManager;
  758. this.channelName = channelName;
  759. this.listenerId = listenerId;
  760. this.requestId = requestId;
  761. };
  762. CallbackWrapper.prototype.proxy = function(response) {
  763. var message = JSON.stringify({
  764. requestId: this.requestId,
  765. channelName: this.channelName,
  766. msg: response !== undefined ? response : null
  767. });
  768. if ( this.messageManager.sendAsyncMessage ) {
  769. this.messageManager.sendAsyncMessage(this.listenerId, message);
  770. } else {
  771. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  772. }
  773. // Mark for reuse
  774. this.messageManager =
  775. this.channelName =
  776. this.requestId =
  777. this.listenerId = null;
  778. CallbackWrapper.junkyard.push(this);
  779. };
  780. /******************************************************************************/
  781. var httpObserver = {
  782. classDescription: 'net-channel-event-sinks for ' + location.host,
  783. classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  784. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  785. ABORT: Components.results.NS_BINDING_ABORTED,
  786. ACCEPT: Components.results.NS_SUCCEEDED,
  787. // Request types: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  788. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  789. VALID_CSP_TARGETS: 1 << Ci.nsIContentPolicy.TYPE_DOCUMENT |
  790. 1 << Ci.nsIContentPolicy.TYPE_SUBDOCUMENT,
  791. typeMap: {
  792. 1: 'other',
  793. 2: 'script',
  794. 3: 'image',
  795. 4: 'stylesheet',
  796. 5: 'object',
  797. 6: 'main_frame',
  798. 7: 'sub_frame',
  799. 11: 'xmlhttprequest',
  800. 12: 'object',
  801. 14: 'font'
  802. },
  803. lastRequest: {
  804. url: null,
  805. type: null,
  806. tabId: null,
  807. frameId: null,
  808. parentFrameId: null,
  809. openerURL: null
  810. },
  811. get componentRegistrar() {
  812. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  813. },
  814. get categoryManager() {
  815. return Cc['@mozilla.org/categorymanager;1']
  816. .getService(Ci.nsICategoryManager);
  817. },
  818. QueryInterface: (function() {
  819. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  820. return XPCOMUtils.generateQI([
  821. Ci.nsIFactory,
  822. Ci.nsIObserver,
  823. Ci.nsIChannelEventSink,
  824. Ci.nsISupportsWeakReference
  825. ]);
  826. })(),
  827. createInstance: function(outer, iid) {
  828. if ( outer ) {
  829. throw Components.results.NS_ERROR_NO_AGGREGATION;
  830. }
  831. return this.QueryInterface(iid);
  832. },
  833. register: function() {
  834. Services.obs.addObserver(this, 'http-on-opening-request', true);
  835. Services.obs.addObserver(this, 'http-on-examine-response', true);
  836. this.componentRegistrar.registerFactory(
  837. this.classID,
  838. this.classDescription,
  839. this.contractID,
  840. this
  841. );
  842. this.categoryManager.addCategoryEntry(
  843. 'net-channel-event-sinks',
  844. this.contractID,
  845. this.contractID,
  846. false,
  847. true
  848. );
  849. },
  850. unregister: function() {
  851. Services.obs.removeObserver(this, 'http-on-opening-request');
  852. Services.obs.removeObserver(this, 'http-on-examine-response');
  853. this.componentRegistrar.unregisterFactory(this.classID, this);
  854. this.categoryManager.deleteCategoryEntry(
  855. 'net-channel-event-sinks',
  856. this.contractID,
  857. false
  858. );
  859. },
  860. handlePopup: function(URI, tabId, sourceTabId) {
  861. if ( !sourceTabId ) {
  862. return false;
  863. }
  864. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  865. return false;
  866. }
  867. var result = vAPI.tabs.onPopup({
  868. tabId: tabId,
  869. sourceTabId: sourceTabId,
  870. url: URI.asciiSpec
  871. });
  872. return result === true;
  873. },
  874. handleRequest: function(channel, URI, details) {
  875. var onBeforeRequest = vAPI.net.onBeforeRequest;
  876. var type = this.typeMap[details.type] || 'other';
  877. if ( onBeforeRequest.types.has(type) === false ) {
  878. return false;
  879. }
  880. var result = onBeforeRequest.callback({
  881. frameId: details.frameId,
  882. hostname: URI.asciiHost,
  883. parentFrameId: details.parentFrameId,
  884. tabId: details.tabId,
  885. type: type,
  886. url: URI.asciiSpec
  887. });
  888. if ( !result || typeof result !== 'object' ) {
  889. return false;
  890. }
  891. if ( result.cancel === true ) {
  892. channel.cancel(this.ABORT);
  893. return true;
  894. }
  895. if ( result.redirectUrl ) {
  896. channel.redirectionLimit = 1;
  897. channel.redirectTo(
  898. Services.io.newURI(result.redirectUrl, null, null)
  899. );
  900. return true;
  901. }
  902. return false;
  903. },
  904. observe: function(channel, topic) {
  905. if ( !(channel instanceof Ci.nsIHttpChannel) ) {
  906. return;
  907. }
  908. var reqDataKey = location.host + 'reqdata';
  909. var URI = channel.URI;
  910. var channelData, result;
  911. if ( topic === 'http-on-examine-response' ) {
  912. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  913. return;
  914. }
  915. try {
  916. /*[
  917. type,
  918. tabId,
  919. sourceTabId - given if it was a popup,
  920. frameId,
  921. parentFrameId
  922. ]*/
  923. channelData = channel.getProperty(reqDataKey);
  924. } catch (ex) {
  925. return;
  926. }
  927. if ( !channelData ) {
  928. return;
  929. }
  930. if ( (1 << channelData[0] & this.VALID_CSP_TARGETS) === 0 ) {
  931. return;
  932. }
  933. topic = 'Content-Security-Policy';
  934. try {
  935. result = channel.getResponseHeader(topic);
  936. } catch (ex) {
  937. result = null;
  938. }
  939. result = vAPI.net.onHeadersReceived.callback({
  940. hostname: URI.asciiHost,
  941. parentFrameId: channelData[4],
  942. responseHeaders: result ? [{name: topic, value: result}] : [],
  943. tabId: channelData[1],
  944. url: URI.asciiSpec
  945. });
  946. if ( result ) {
  947. channel.setResponseHeader(
  948. topic,
  949. result.responseHeaders.pop().value,
  950. true
  951. );
  952. }
  953. return;
  954. }
  955. // http-on-opening-request
  956. var lastRequest = this.lastRequest;
  957. if ( lastRequest.url === null ) {
  958. this.handleRequest(channel, URI, {
  959. tabId: vAPI.noTabId,
  960. type: channel.loadInfo && channel.loadInfo.contentPolicyType || 1
  961. });
  962. return;
  963. }
  964. // Important! When loading file via XHR for mirroring,
  965. // the URL will be the same, so it could fall into an infinite loop
  966. lastRequest.url = null;
  967. var sourceTabId = null;
  968. // Popup candidate (only for main_frame type)
  969. if ( lastRequest.openerURL ) {
  970. for ( var tab of vAPI.tabs.getAll() ) {
  971. var tabURI = tab.linkedBrowser.currentURI;
  972. // Probably isn't the best method to identify the source tab
  973. if ( tabURI.spec !== lastRequest.openerURL ) {
  974. continue;
  975. }
  976. sourceTabId = vAPI.tabs.getTabId(tab);
  977. if ( sourceTabId !== lastRequest.tabId ) {
  978. break;
  979. }
  980. sourceTabId = null;
  981. }
  982. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  983. channel.cancel(this.ABORT);
  984. return;
  985. }
  986. }
  987. if ( lastRequest.type === this.MAIN_FRAME && lastRequest.frameId === 0 ) {
  988. vAPI.tabs.onNavigation({
  989. frameId: 0,
  990. tabId: lastRequest.tabId,
  991. url: URI.asciiSpec
  992. });
  993. }
  994. if ( this.handleRequest(channel, URI, lastRequest) ) {
  995. return;
  996. }
  997. // If request is not handled we may use the data in on-modify-request
  998. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  999. channel.setProperty(
  1000. reqDataKey,
  1001. [
  1002. lastRequest.type,
  1003. lastRequest.tabId,
  1004. sourceTabId,
  1005. lastRequest.frameId,
  1006. lastRequest.parentFrameId
  1007. ]
  1008. );
  1009. }
  1010. },
  1011. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1012. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1013. var result = this.ACCEPT;
  1014. // If error thrown, the redirect will fail
  1015. try {
  1016. // skip internal redirects?
  1017. /*if ( flags & 4 ) {
  1018. console.log('internal redirect skipped');
  1019. return;
  1020. }*/
  1021. var URI = newChannel.URI;
  1022. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1023. return;
  1024. }
  1025. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1026. return;
  1027. }
  1028. // TODO: what if a behind-the-scene request is being redirected?
  1029. // This data is present only for tabbed requests, so if this throws,
  1030. // the redirection won't be evaluated and canceled (if necessary)
  1031. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  1032. if ( this.handlePopup(URI, channelData[1], channelData[2]) ) {
  1033. result = this.ABORT;
  1034. return;
  1035. }
  1036. var details = {
  1037. type: channelData[0],
  1038. tabId: channelData[1],
  1039. frameId: channelData[3],
  1040. parentFrameId: channelData[4]
  1041. };
  1042. if ( this.handleRequest(newChannel, URI, details) ) {
  1043. result = this.ABORT;
  1044. return;
  1045. }
  1046. // Carry the data on in case of multiple redirects
  1047. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1048. newChannel.setProperty(location.host + 'reqdata', channelData);
  1049. }
  1050. } catch (ex) {
  1051. // console.error(ex);
  1052. } finally {
  1053. callback.onRedirectVerifyCallback(result);
  1054. }
  1055. }
  1056. };
  1057. /******************************************************************************/
  1058. vAPI.net = {};
  1059. /******************************************************************************/
  1060. vAPI.net.registerListeners = function() {
  1061. // Since it's not used
  1062. this.onBeforeSendHeaders = null;
  1063. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  1064. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1065. var shouldLoadListener = function(e) {
  1066. var details = e.data;
  1067. var lastRequest = httpObserver.lastRequest;
  1068. lastRequest.url = details.url;
  1069. lastRequest.type = details.type;
  1070. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  1071. lastRequest.frameId = details.frameId;
  1072. lastRequest.parentFrameId = details.parentFrameId;
  1073. lastRequest.openerURL = details.openerURL;
  1074. };
  1075. vAPI.messaging.globalMessageManager.addMessageListener(
  1076. shouldLoadListenerMessageName,
  1077. shouldLoadListener
  1078. );
  1079. httpObserver.register();
  1080. cleanupTasks.push(function() {
  1081. vAPI.messaging.globalMessageManager.removeMessageListener(
  1082. shouldLoadListenerMessageName,
  1083. shouldLoadListener
  1084. );
  1085. httpObserver.unregister();
  1086. });
  1087. };
  1088. /******************************************************************************/
  1089. vAPI.toolbarButton = {
  1090. id: location.host + '-button',
  1091. type: 'view',
  1092. viewId: location.host + '-panel',
  1093. label: vAPI.app.name,
  1094. tooltiptext: vAPI.app.name,
  1095. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1096. };
  1097. /******************************************************************************/
  1098. vAPI.toolbarButton.init = function() {
  1099. var CustomizableUI;
  1100. try {
  1101. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1102. } catch (ex) {
  1103. return;
  1104. }
  1105. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1106. this.styleURI = [
  1107. '#' + this.id + ' {',
  1108. 'list-style-image: url(',
  1109. vAPI.getURL('img/browsericons/icon16-off.svg'),
  1110. ');',
  1111. '}',
  1112. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1113. 'width: 160px;',
  1114. 'height: 290px;',
  1115. 'overflow: hidden !important;',
  1116. '}'
  1117. ];
  1118. var platformVersion = Services.appinfo.platformVersion;
  1119. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1120. this.styleURI.push(
  1121. '#' + this.id + '[badge]:not([badge=""])::after {',
  1122. 'position: absolute;',
  1123. 'margin-left: -16px;',
  1124. 'margin-top: 3px;',
  1125. 'padding: 1px 2px;',
  1126. 'font-size: 9px;',
  1127. 'font-weight: bold;',
  1128. 'color: #fff;',
  1129. 'background: #666;',
  1130. 'content: attr(badge);',
  1131. '}'
  1132. );
  1133. } else {
  1134. this.CUIEvents = {};
  1135. this.CUIEvents.onCustomizeEnd = function() {
  1136. var wId = vAPI.toolbarButton.id;
  1137. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1138. for ( var win of vAPI.tabs.getWindows() ) {
  1139. var button = win.document.getElementById(wId);
  1140. if ( buttonInPanel ) {
  1141. button.classList.remove('badged-button');
  1142. continue;
  1143. }
  1144. if ( button === null ) {
  1145. continue;
  1146. }
  1147. button.classList.add('badged-button');
  1148. }
  1149. if ( buttonInPanel ) {
  1150. return;
  1151. }
  1152. // Anonymous elements need some time to be reachable
  1153. setTimeout(this.updateBadgeStyle, 250);
  1154. }.bind(this.CUIEvents);
  1155. this.CUIEvents.updateBadgeStyle = function() {
  1156. var css = [
  1157. 'background: #666',
  1158. 'color: #fff'
  1159. ].join(';');
  1160. for ( var win of vAPI.tabs.getWindows() ) {
  1161. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1162. if ( button === null ) {
  1163. continue;
  1164. }
  1165. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1166. button,
  1167. 'class',
  1168. 'toolbarbutton-badge'
  1169. );
  1170. if ( !badge ) {
  1171. return;
  1172. }
  1173. badge.style.cssText = css;
  1174. }
  1175. };
  1176. this.onCreated = function(button) {
  1177. button.setAttribute('badge', '');
  1178. setTimeout(this.CUIEvents.onCustomizeEnd, 250);
  1179. };
  1180. CustomizableUI.addListener(this.CUIEvents);
  1181. }
  1182. this.styleURI = Services.io.newURI(
  1183. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1184. null,
  1185. null
  1186. );
  1187. this.closePopup = function({target}) {
  1188. CustomizableUI.hidePanelForNode(
  1189. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1190. );
  1191. };
  1192. CustomizableUI.createWidget(this);
  1193. vAPI.messaging.globalMessageManager.addMessageListener(
  1194. location.host + ':closePopup',
  1195. this.closePopup
  1196. );
  1197. cleanupTasks.push(function() {
  1198. if ( this.CUIEvents ) {
  1199. CustomizableUI.removeListener(this.CUIEvents);
  1200. }
  1201. CustomizableUI.destroyWidget(this.id);
  1202. vAPI.messaging.globalMessageManager.removeMessageListener(
  1203. location.host + ':closePopup',
  1204. this.closePopup
  1205. );
  1206. for ( var win of vAPI.tabs.getWindows() ) {
  1207. var panel = win.document.getElementById(this.viewId);
  1208. panel.parentNode.removeChild(panel);
  1209. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1210. .getInterface(Ci.nsIDOMWindowUtils)
  1211. .removeSheet(this.styleURI, 1);
  1212. }
  1213. }.bind(this));
  1214. };
  1215. /******************************************************************************/
  1216. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1217. var panel = doc.createElement('panelview');
  1218. panel.setAttribute('id', this.viewId);
  1219. var iframe = doc.createElement('iframe');
  1220. iframe.setAttribute('type', 'content');
  1221. doc.getElementById('PanelUI-multiView')
  1222. .appendChild(panel)
  1223. .appendChild(iframe);
  1224. var updateTimer = null;
  1225. var delayedResize = function() {
  1226. if ( updateTimer ) {
  1227. return;
  1228. }
  1229. updateTimer = setTimeout(resizePopup, 10);
  1230. };
  1231. var resizePopup = function() {
  1232. updateTimer = null;
  1233. var body = iframe.contentDocument.body;
  1234. panel.parentNode.style.maxWidth = 'none';
  1235. // https://github.com/gorhill/uBlock/issues/730
  1236. // Voodoo programming: this recipe works
  1237. panel.style.height = iframe.style.height = body.clientHeight.toString() + 'px';
  1238. panel.style.width = iframe.style.width = body.clientWidth.toString() + 'px';
  1239. if ( iframe.clientHeight !== body.clientHeight || iframe.clientWidth !== body.clientWidth ) {
  1240. delayedResize();
  1241. }
  1242. };
  1243. var onPopupReady = function() {
  1244. var win = this.contentWindow;
  1245. if ( !win || win.location.host !== location.host ) {
  1246. return;
  1247. }
  1248. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1249. attributes: true,
  1250. characterData: true,
  1251. subtree: true
  1252. });
  1253. delayedResize();
  1254. };
  1255. iframe.addEventListener('load', onPopupReady, true);
  1256. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1257. .getInterface(Ci.nsIDOMWindowUtils)
  1258. .loadSheet(this.styleURI, 1);
  1259. };
  1260. /******************************************************************************/
  1261. vAPI.toolbarButton.onViewShowing = function({target}) {
  1262. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1263. };
  1264. /******************************************************************************/
  1265. vAPI.toolbarButton.onViewHiding = function({target}) {
  1266. target.parentNode.style.maxWidth = '';
  1267. target.firstChild.setAttribute('src', 'about:blank');
  1268. };
  1269. /******************************************************************************/
  1270. vAPI.toolbarButton.init();
  1271. /******************************************************************************/
  1272. vAPI.contextMenu = {
  1273. contextMap: {
  1274. frame: 'inFrame',
  1275. link: 'onLink',
  1276. image: 'onImage',
  1277. audio: 'onAudio',
  1278. video: 'onVideo',
  1279. editable: 'onEditableArea'
  1280. }
  1281. };
  1282. /******************************************************************************/
  1283. vAPI.contextMenu.displayMenuItem = function({target}) {
  1284. var doc = target.ownerDocument;
  1285. var gContextMenu = doc.defaultView.gContextMenu;
  1286. if ( !gContextMenu.browser ) {
  1287. return;
  1288. }
  1289. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1290. var currentURI = gContextMenu.browser.currentURI;
  1291. // https://github.com/gorhill/uBlock/issues/105
  1292. // TODO: Should the element picker works on any kind of pages?
  1293. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1294. menuitem.hidden = true;
  1295. return;
  1296. }
  1297. var ctx = vAPI.contextMenu.contexts;
  1298. if ( !ctx ) {
  1299. menuitem.hidden = false;
  1300. return;
  1301. }
  1302. var ctxMap = vAPI.contextMenu.contextMap;
  1303. for ( var context of ctx ) {
  1304. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1305. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1306. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1307. menuitem.hidden = false;
  1308. return;
  1309. }
  1310. if ( gContextMenu[ctxMap[context]] ) {
  1311. menuitem.hidden = false;
  1312. return;
  1313. }
  1314. }
  1315. menuitem.hidden = true;
  1316. };
  1317. /******************************************************************************/
  1318. vAPI.contextMenu.register = function(doc) {
  1319. if ( !this.menuItemId ) {
  1320. return;
  1321. }
  1322. if ( vAPI.fennec ) {
  1323. // TODO https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/NativeWindow/contextmenus/add
  1324. /*var nativeWindow = doc.defaultView.NativeWindow;
  1325. contextId = nativeWindow.contextmenus.add(
  1326. this.menuLabel,
  1327. nativeWindow.contextmenus.linkOpenableContext,
  1328. this.onCommand
  1329. );*/
  1330. return;
  1331. }
  1332. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1333. var menuitem = doc.createElement('menuitem');
  1334. menuitem.setAttribute('id', this.menuItemId);
  1335. menuitem.setAttribute('label', this.menuLabel);
  1336. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1337. menuitem.setAttribute('class', 'menuitem-iconic');
  1338. menuitem.addEventListener('command', this.onCommand);
  1339. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1340. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1341. };
  1342. /******************************************************************************/
  1343. vAPI.contextMenu.unregister = function(doc) {
  1344. if ( !this.menuItemId ) {
  1345. return;
  1346. }
  1347. if ( vAPI.fennec ) {
  1348. // TODO
  1349. return;
  1350. }
  1351. var menuitem = doc.getElementById(this.menuItemId);
  1352. var contextMenu = menuitem.parentNode;
  1353. menuitem.removeEventListener('command', this.onCommand);
  1354. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1355. contextMenu.removeChild(menuitem);
  1356. };
  1357. /******************************************************************************/
  1358. vAPI.contextMenu.create = function(details, callback) {
  1359. this.menuItemId = details.id;
  1360. this.menuLabel = details.title;
  1361. this.contexts = details.contexts;
  1362. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1363. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1364. } else {
  1365. // default in Chrome
  1366. this.contexts = ['page'];
  1367. }
  1368. this.onCommand = function() {
  1369. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1370. var details = {
  1371. menuItemId: this.id
  1372. };
  1373. if ( gContextMenu.inFrame ) {
  1374. details.tagName = 'iframe';
  1375. // Probably won't work with e01s
  1376. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1377. } else if ( gContextMenu.onImage ) {
  1378. details.tagName = 'img';
  1379. details.srcUrl = gContextMenu.mediaURL;
  1380. } else if ( gContextMenu.onAudio ) {
  1381. details.tagName = 'audio';
  1382. details.srcUrl = gContextMenu.mediaURL;
  1383. } else if ( gContextMenu.onVideo ) {
  1384. details.tagName = 'video';
  1385. details.srcUrl = gContextMenu.mediaURL;
  1386. } else if ( gContextMenu.onLink ) {
  1387. details.tagName = 'a';
  1388. details.linkUrl = gContextMenu.linkURL;
  1389. }
  1390. callback(details, {
  1391. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1392. url: gContextMenu.browser.currentURI.asciiSpec
  1393. });
  1394. };
  1395. for ( var win of vAPI.tabs.getWindows() ) {
  1396. this.register(win.document);
  1397. }
  1398. };
  1399. /******************************************************************************/
  1400. vAPI.lastError = function() {
  1401. return null;
  1402. };
  1403. /******************************************************************************/
  1404. // This is called only once, when everything has been loaded in memory after
  1405. // the extension was launched. It can be used to inject content scripts
  1406. // in already opened web pages, to remove whatever nuisance could make it to
  1407. // the web pages before uBlock was ready.
  1408. vAPI.onLoadAllCompleted = function() {};
  1409. /******************************************************************************/
  1410. // Likelihood is that we do not have to punycode: given punycode overhead,
  1411. // it's faster to check and skip than do it unconditionally all the time.
  1412. var punycodeHostname = punycode.toASCII;
  1413. var isNotASCII = /[^\x21-\x7F]/;
  1414. vAPI.punycodeHostname = function(hostname) {
  1415. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1416. };
  1417. vAPI.punycodeURL = function(url) {
  1418. if ( isNotASCII.test(url) ) {
  1419. return Services.io.newURI(url, null, null).asciiSpec;
  1420. }
  1421. return url;
  1422. };
  1423. /******************************************************************************/
  1424. // clean up when the extension is disabled
  1425. window.addEventListener('unload', function() {
  1426. for ( var cleanup of cleanupTasks ) {
  1427. cleanup();
  1428. }
  1429. // frameModule needs to be cleared too
  1430. var frameModule = {};
  1431. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1432. frameModule.contentObserver.unregister();
  1433. Cu.unload(vAPI.getURL('frameModule.js'));
  1434. });
  1435. /******************************************************************************/
  1436. })();
  1437. /******************************************************************************/