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.

1254 lines
36 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. /* global Services, CustomizableUI */
  17. // For background page
  18. /******************************************************************************/
  19. (function() {
  20. 'use strict';
  21. /******************************************************************************/
  22. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  23. Cu['import']('resource://gre/modules/Services.jsm');
  24. Cu['import']('resource:///modules/CustomizableUI.jsm');
  25. /******************************************************************************/
  26. self.vAPI = self.vAPI || {};
  27. vAPI.firefox = true;
  28. /******************************************************************************/
  29. // TODO: read these data from somewhere...
  30. vAPI.app = {
  31. name: 'µBlock',
  32. version: '0.8.2.3'
  33. };
  34. /******************************************************************************/
  35. vAPI.app.restart = function() {
  36. // Observing in bootstrap.js
  37. Services.obs.notifyObservers(null, location.host + '-restart', null);
  38. };
  39. /******************************************************************************/
  40. // List of things that needs to be destroyed when disabling the extension
  41. // Only functions should be added to it
  42. vAPI.unload = [];
  43. /******************************************************************************/
  44. var SQLite = {
  45. open: function() {
  46. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  47. path.append('extension-data');
  48. if ( !path.exists() ) {
  49. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  50. }
  51. if ( !path.isDirectory() ) {
  52. throw Error('Should be a directory...');
  53. }
  54. path.append(location.host + '.sqlite');
  55. this.db = Services.storage.openDatabase(path);
  56. this.db.executeSimpleSQL(
  57. 'CREATE TABLE IF NOT EXISTS settings' +
  58. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  59. );
  60. vAPI.unload.push(function() {
  61. // VACUUM somewhere else, instead on unload?
  62. SQLite.run('VACUUM');
  63. SQLite.db.asyncClose();
  64. });
  65. },
  66. run: function(query, values, callback) {
  67. if ( !this.db ) {
  68. this.open();
  69. }
  70. var result = {};
  71. query = this.db.createAsyncStatement(query);
  72. if ( Array.isArray(values) && values.length ) {
  73. var i = values.length;
  74. while ( i-- ) {
  75. query.bindByIndex(i, values[i]);
  76. }
  77. }
  78. query.executeAsync({
  79. handleResult: function(rows) {
  80. if ( !rows || typeof callback !== 'function' ) {
  81. return;
  82. }
  83. var row;
  84. while ( row = rows.getNextRow() ) {
  85. // we assume that there will be two columns, since we're
  86. // using it only for preferences
  87. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  88. }
  89. },
  90. handleCompletion: function(reason) {
  91. if ( typeof callback === 'function' && reason === 0 ) {
  92. callback(result);
  93. }
  94. },
  95. handleError: function(error) {
  96. console.error('SQLite error ', error.result, error.message);
  97. }
  98. });
  99. }
  100. };
  101. /******************************************************************************/
  102. vAPI.storage = {
  103. QUOTA_BYTES: 100 * 1024 * 1024,
  104. sqlWhere: function(col, params) {
  105. if ( params > 0 ) {
  106. params = Array(params + 1).join('?, ').slice(0, -2);
  107. return ' WHERE ' + col + ' IN (' + params + ')';
  108. }
  109. return '';
  110. },
  111. get: function(details, callback) {
  112. if ( typeof callback !== 'function' ) {
  113. return;
  114. }
  115. var values = [], defaults = false;
  116. if ( details !== null ) {
  117. if ( Array.isArray(details) ) {
  118. values = details;
  119. } else if ( typeof details === 'object' ) {
  120. defaults = true;
  121. values = Object.keys(details);
  122. } else {
  123. values = [details.toString()];
  124. }
  125. }
  126. SQLite.run(
  127. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  128. values,
  129. function(result) {
  130. var key;
  131. for ( key in result ) {
  132. result[key] = JSON.parse(result[key]);
  133. }
  134. if ( defaults ) {
  135. for ( key in details ) {
  136. if ( result[key] === undefined ) {
  137. result[key] = details[key];
  138. }
  139. }
  140. }
  141. callback(result);
  142. }
  143. );
  144. },
  145. set: function(details, callback) {
  146. var key, values = [], placeholders = [];
  147. for ( key in details ) {
  148. values.push(key);
  149. values.push(JSON.stringify(details[key]));
  150. placeholders.push('?, ?');
  151. }
  152. if ( !values.length ) {
  153. return;
  154. }
  155. SQLite.run(
  156. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  157. placeholders.join(' UNION SELECT '),
  158. values,
  159. callback
  160. );
  161. },
  162. remove: function(keys, callback) {
  163. if ( typeof keys === 'string' ) {
  164. keys = [keys];
  165. }
  166. SQLite.run(
  167. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  168. keys,
  169. callback
  170. );
  171. },
  172. clear: function(callback) {
  173. SQLite.run('DELETE FROM settings');
  174. SQLite.run('VACUUM', null, callback);
  175. },
  176. getBytesInUse: function(keys, callback) {
  177. if ( typeof callback !== 'function' ) {
  178. return;
  179. }
  180. SQLite.run(
  181. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  182. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  183. keys,
  184. function(result) {
  185. callback(result.size);
  186. }
  187. );
  188. }
  189. };
  190. /******************************************************************************/
  191. var windowWatcher = {
  192. onTabClose: function(e) {
  193. var tabId = vAPI.tabs.getTabId(e.target);
  194. vAPI.tabs.onClosed(tabId);
  195. delete vAPI.tabIcons[tabId];
  196. },
  197. onTabSelect: function(e) {
  198. vAPI.setIcon(
  199. vAPI.tabs.getTabId(e.target),
  200. e.target.ownerDocument.defaultView
  201. );
  202. },
  203. onReady: function(e) {
  204. if ( e ) {
  205. this.removeEventListener(e.type, windowWatcher.onReady);
  206. }
  207. var wintype = this.document.documentElement.getAttribute('windowtype');
  208. if ( wintype !== 'navigator:browser' ) {
  209. return;
  210. }
  211. if ( !this.gBrowser || !this.gBrowser.tabContainer ) {
  212. return;
  213. }
  214. var tC = this.gBrowser.tabContainer;
  215. this.gBrowser.addTabsProgressListener(tabsProgressListener);
  216. tC.addEventListener('TabClose', windowWatcher.onTabClose);
  217. tC.addEventListener('TabSelect', windowWatcher.onTabSelect);
  218. vAPI.toolbarButton.register(this.document);
  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 tabsProgressListener = {
  230. onLocationChange: function(browser, webProgress, request, location, flags) {
  231. if ( !webProgress.isTopLevel ) {
  232. return;
  233. }
  234. var tabId = vAPI.tabs.getTabId(browser);
  235. if ( flags & 1 ) {
  236. vAPI.tabs.onUpdated(tabId, {url: location.spec}, {
  237. frameId: 0,
  238. tabId: tabId,
  239. url: browser.currentURI.spec
  240. });
  241. } else {
  242. vAPI.tabs.onNavigation({
  243. frameId: 0,
  244. tabId: tabId,
  245. url: location.spec
  246. });
  247. }
  248. }
  249. };
  250. /******************************************************************************/
  251. vAPI.tabs = {};
  252. /******************************************************************************/
  253. vAPI.tabs.registerListeners = function() {
  254. // onNavigation and onUpdated handled with tabsProgressListener
  255. // onClosed - handled in windowWatcher.onTabClose
  256. // onPopup ?
  257. for ( var win of this.getWindows() ) {
  258. windowWatcher.onReady.call(win);
  259. }
  260. Services.ww.registerNotification(windowWatcher);
  261. vAPI.toolbarButton.init();
  262. vAPI.unload.push(function() {
  263. Services.ww.unregisterNotification(windowWatcher);
  264. for ( var win of vAPI.tabs.getWindows() ) {
  265. vAPI.toolbarButton.unregister(win.document);
  266. vAPI.contextMenu.unregister(win.document);
  267. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  268. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  269. var tC = win.gBrowser.tabContainer;
  270. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  271. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  272. // close extension tabs
  273. for ( var tab of win.gBrowser.tabs ) {
  274. var URI = tab.linkedBrowser.currentURI;
  275. if ( URI.scheme === 'chrome' && URI.host === location.host ) {
  276. win.gBrowser.removeTab(tab);
  277. }
  278. }
  279. }
  280. });
  281. };
  282. /******************************************************************************/
  283. vAPI.tabs.getTabId = function(target) {
  284. if ( target.linkedPanel ) {
  285. return target.linkedPanel.slice(6);
  286. }
  287. var i, gBrowser = target.ownerDocument.defaultView.gBrowser;
  288. // This should be more efficient from version 35
  289. if ( gBrowser.getTabForBrowser ) {
  290. i = gBrowser.getTabForBrowser(target);
  291. return i ? i.linkedPanel.slice(6) : -1;
  292. }
  293. i = gBrowser.browsers.indexOf(target);
  294. if ( i !== -1 ) {
  295. i = gBrowser.tabs[i].linkedPanel.slice(6);
  296. }
  297. return i;
  298. };
  299. /******************************************************************************/
  300. vAPI.tabs.get = function(tabId, callback) {
  301. var tab, windows;
  302. if ( tabId === null ) {
  303. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  304. tabId = vAPI.tabs.getTabId(tab);
  305. } else {
  306. windows = this.getWindows();
  307. for ( var win of windows ) {
  308. tab = win.gBrowser.tabContainer.querySelector(
  309. 'tab[linkedpanel="panel-' + tabId + '"]'
  310. );
  311. if ( tab ) {
  312. break;
  313. }
  314. }
  315. }
  316. // for internal use
  317. if ( tab && typeof callback !== 'function' ) {
  318. return tab;
  319. }
  320. if ( !tab ) {
  321. callback();
  322. return;
  323. }
  324. var browser = tab.linkedBrowser;
  325. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  326. if ( !windows ) {
  327. windows = this.getWindows();
  328. }
  329. callback({
  330. id: tabId,
  331. index: gBrowser.browsers.indexOf(browser),
  332. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  333. active: tab === gBrowser.selectedTab,
  334. url: browser.currentURI.spec,
  335. title: tab.label
  336. });
  337. };
  338. /******************************************************************************/
  339. vAPI.tabs.getAll = function(window) {
  340. var win, tab, tabs = [];
  341. for ( win of this.getWindows() ) {
  342. if ( window && window !== win ) {
  343. continue;
  344. }
  345. for ( tab of win.gBrowser.tabs ) {
  346. tabs.push(tab);
  347. }
  348. }
  349. return tabs;
  350. };
  351. /******************************************************************************/
  352. vAPI.tabs.getWindows = function() {
  353. var winumerator = Services.wm.getEnumerator('navigator:browser');
  354. var windows = [];
  355. while ( winumerator.hasMoreElements() ) {
  356. var win = winumerator.getNext();
  357. if ( !win.closed ) {
  358. windows.push(win);
  359. }
  360. }
  361. return windows;
  362. };
  363. /******************************************************************************/
  364. // properties of the details object:
  365. // url: 'URL', // the address that will be opened
  366. // tabId: 1, // the tab is used if set, instead of creating a new one
  367. // index: -1, // undefined: end of the list, -1: following tab, or after index
  368. // active: false, // opens the tab in background - true and undefined: foreground
  369. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  370. vAPI.tabs.open = function(details) {
  371. if ( !details.url ) {
  372. return null;
  373. }
  374. // extension pages
  375. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  376. details.url = vAPI.getURL(details.url);
  377. }
  378. var tab, tabs;
  379. if ( details.select ) {
  380. var rgxHash = /#.*/;
  381. // this is questionable
  382. var url = details.url.replace(rgxHash, '');
  383. tabs = this.getAll();
  384. for ( tab of tabs ) {
  385. var browser = tab.linkedBrowser;
  386. if ( browser.currentURI.spec.replace(rgxHash, '') === url ) {
  387. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  388. return;
  389. }
  390. }
  391. }
  392. if ( details.active === undefined ) {
  393. details.active = true;
  394. }
  395. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  396. if ( details.index === -1 ) {
  397. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  398. }
  399. if ( details.tabId ) {
  400. tabs = tabs || this.getAll();
  401. for ( tab of tabs ) {
  402. if ( vAPI.tabs.getTabId(tab) === details.tabId ) {
  403. tab.linkedBrowser.loadURI(details.url);
  404. return;
  405. }
  406. }
  407. }
  408. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  409. if ( details.index !== undefined ) {
  410. gBrowser.moveTabTo(tab, details.index);
  411. }
  412. };
  413. /******************************************************************************/
  414. vAPI.tabs.close = function(tabIds) {
  415. if ( !Array.isArray(tabIds) ) {
  416. tabIds = [tabIds];
  417. }
  418. tabIds = tabIds.map(function(tabId) {
  419. return 'tab[linkedpanel="panel-' + tabId + '"]';
  420. }).join(',');
  421. for ( var win of this.getWindows() ) {
  422. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  423. if ( !tabs ) {
  424. continue;
  425. }
  426. for ( var tab of tabs ) {
  427. win.gBrowser.removeTab(tab);
  428. }
  429. }
  430. };
  431. /******************************************************************************/
  432. vAPI.tabs.injectScript = function(tabId, details, callback) {
  433. var tab = vAPI.tabs.get(tabId);
  434. if ( !tab ) {
  435. return;
  436. }
  437. if ( details.file ) {
  438. details.file = vAPI.getURL(details.file);
  439. }
  440. tab.linkedBrowser.messageManager.sendAsyncMessage(
  441. location.host + ':broadcast',
  442. JSON.stringify({
  443. broadcast: true,
  444. channelName: 'vAPI',
  445. msg: {
  446. cmd: 'injectScript',
  447. details: details
  448. }
  449. })
  450. );
  451. if ( typeof callback === 'function' ) {
  452. setTimeout(callback, 13);
  453. }
  454. };
  455. /******************************************************************************/
  456. vAPI.tabIcons = { /*tabId: {badge: 0, img: boolean}*/ };
  457. vAPI.setIcon = function(tabId, iconStatus, badge) {
  458. // If badge is undefined, then setIcon was called from the TabSelect event
  459. var curWin = badge === undefined
  460. ? iconStatus
  461. : Services.wm.getMostRecentWindow('navigator:browser');
  462. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  463. // from 'TabSelect' event
  464. if ( tabId === undefined ) {
  465. tabId = curTabId;
  466. } else if ( badge !== undefined ) {
  467. vAPI.tabIcons[tabId] = {
  468. badge: badge,
  469. img: iconStatus === 'on'
  470. };
  471. }
  472. if ( tabId !== curTabId ) {
  473. return;
  474. }
  475. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  476. if ( !button ) {
  477. return;
  478. }
  479. /*if ( !button.classList.contains('badged-button') ) {
  480. button.classList.add('badged-button');
  481. }*/
  482. var icon = vAPI.tabIcons[tabId];
  483. button.setAttribute('badge', icon && icon.badge || '');
  484. iconStatus = !button.image || !icon || !icon.img ? '-off' : '';
  485. button.image = vAPI.getURL('img/browsericons/icon16' + iconStatus + '.svg');
  486. };
  487. /******************************************************************************/
  488. vAPI.toolbarButton = {
  489. widgetId: location.host + '-button',
  490. panelId: location.host + '-panel'
  491. };
  492. /******************************************************************************/
  493. vAPI.toolbarButton.init = function() {
  494. CustomizableUI.createWidget({
  495. id: this.widgetId,
  496. type: 'view',
  497. viewId: this.panelId,
  498. defaultArea: CustomizableUI.AREA_NAVBAR,
  499. label: vAPI.app.name,
  500. tooltiptext: vAPI.app.name,
  501. onViewShowing: function({target}) {
  502. var hash = CustomizableUI.getWidget(vAPI.toolbarButton.widgetId)
  503. .areaType === CustomizableUI.TYPE_TOOLBAR ? '' : '#body';
  504. target.firstChild.setAttribute(
  505. 'src',
  506. vAPI.getURL('popup.html' + hash)
  507. );
  508. },
  509. onViewHiding: function({target}) {
  510. target.firstChild.setAttribute('src', 'about:blank');
  511. }
  512. });
  513. this.closePopup = function({target}) {
  514. CustomizableUI.hidePanelForNode(
  515. target.ownerDocument.getElementById(vAPI.toolbarButton.panelId)
  516. );
  517. };
  518. vAPI.messaging.globalMessageManager.addMessageListener(
  519. location.host + ':closePopup',
  520. this.closePopup
  521. );
  522. vAPI.unload.push(function() {
  523. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  524. vAPI.messaging.globalMessageManager.removeMessageListener(
  525. location.host + ':closePopup',
  526. vAPI.toolbarButton.closePopup
  527. );
  528. });
  529. };
  530. /******************************************************************************/
  531. // it runs with windowWatcher when a window is opened
  532. // vAPI.tabs.registerListeners initializes it
  533. vAPI.toolbarButton.register = function(doc) {
  534. var panel = doc.createElement('panelview');
  535. panel.setAttribute('id', this.panelId);
  536. var iframe = doc.createElement('iframe');
  537. iframe.setAttribute('type', 'content');
  538. doc.getElementById('PanelUI-multiView')
  539. .appendChild(panel)
  540. .appendChild(iframe);
  541. var updateTimer = null;
  542. var delayedResize = function() {
  543. if ( updateTimer ) {
  544. return;
  545. }
  546. updateTimer = setTimeout(resizePopup, 20);
  547. };
  548. var resizePopup = function() {
  549. var panelStyle = panel.style;
  550. var body = iframe.contentDocument.body;
  551. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  552. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  553. updateTimer = null;
  554. };
  555. var onPopupReady = function() {
  556. var win = this.contentWindow;
  557. if ( !win || win.location.host !== location.host ) {
  558. return;
  559. }
  560. new win.MutationObserver(delayedResize).observe(win.document, {
  561. childList: true,
  562. attributes: true,
  563. characterData: true,
  564. subtree: true
  565. });
  566. delayedResize();
  567. };
  568. iframe.addEventListener('load', onPopupReady, true);
  569. if ( !this.styleURI ) {
  570. this.styleURI = 'data:text/css,' + encodeURIComponent([
  571. '#' + this.widgetId + ' {',
  572. 'list-style-image: url(',
  573. vAPI.getURL('img/browsericons/icon16-off.svg'),
  574. ');',
  575. '}',
  576. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  577. 'position: absolute;',
  578. 'margin-left: -16px;',
  579. 'margin-top: 3px;',
  580. 'padding: 1px 2px;',
  581. 'font-size: 9px;',
  582. 'font-weight: bold;',
  583. 'color: #fff;',
  584. 'background: #666;',
  585. 'content: attr(badge);',
  586. '}',
  587. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  588. 'width: 180px;',
  589. 'height: 310px;',
  590. 'overflow: hidden !important;',
  591. '}'
  592. ].join(''));
  593. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  594. }
  595. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  596. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  597. };
  598. /******************************************************************************/
  599. vAPI.toolbarButton.unregister = function(doc) {
  600. var panel = doc.getElementById(this.panelId);
  601. panel.parentNode.removeChild(panel);
  602. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  603. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  604. };
  605. /******************************************************************************/
  606. vAPI.messaging = {
  607. get globalMessageManager() {
  608. return Cc['@mozilla.org/globalmessagemanager;1']
  609. .getService(Ci.nsIMessageListenerManager);
  610. },
  611. frameScript: vAPI.getURL('frameScript.js'),
  612. listeners: {},
  613. defaultHandler: null,
  614. NOOPFUNC: function(){},
  615. UNHANDLED: 'vAPI.messaging.notHandled'
  616. };
  617. /******************************************************************************/
  618. vAPI.messaging.listen = function(listenerName, callback) {
  619. this.listeners[listenerName] = callback;
  620. };
  621. /******************************************************************************/
  622. vAPI.messaging.onMessage = function({target, data}) {
  623. var messageManager = target.messageManager;
  624. if ( !messageManager ) {
  625. // Message came from a popup, and its message manager is not usable.
  626. // So instead we broadcast to the parent window.
  627. messageManager = target
  628. .webNavigation.QueryInterface(Ci.nsIDocShell)
  629. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  630. }
  631. var listenerId = data.channelName.split('|');
  632. var requestId = data.requestId;
  633. var channelName = listenerId[1];
  634. listenerId = listenerId[0];
  635. var callback = vAPI.messaging.NOOPFUNC;
  636. if ( requestId !== undefined ) {
  637. callback = function(response) {
  638. var message = JSON.stringify({
  639. requestId: requestId,
  640. channelName: channelName,
  641. msg: response !== undefined ? response : null
  642. });
  643. if ( messageManager.sendAsyncMessage ) {
  644. messageManager.sendAsyncMessage(listenerId, message);
  645. } else {
  646. messageManager.broadcastAsyncMessage(listenerId, message);
  647. }
  648. };
  649. }
  650. var sender = {
  651. tab: {
  652. id: vAPI.tabs.getTabId(target)
  653. }
  654. };
  655. // Specific handler
  656. var r = vAPI.messaging.UNHANDLED;
  657. var listener = vAPI.messaging.listeners[channelName];
  658. if ( typeof listener === 'function' ) {
  659. r = listener(data.msg, sender, callback);
  660. }
  661. if ( r !== vAPI.messaging.UNHANDLED ) {
  662. return;
  663. }
  664. // Default handler
  665. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  666. if ( r !== vAPI.messaging.UNHANDLED ) {
  667. return;
  668. }
  669. console.error('µBlock> messaging > unknown request: %o', data);
  670. // Unhandled:
  671. // Need to callback anyways in case caller expected an answer, or
  672. // else there is a memory leak on caller's side
  673. callback();
  674. };
  675. /******************************************************************************/
  676. vAPI.messaging.setup = function(defaultHandler) {
  677. // Already setup?
  678. if ( this.defaultHandler !== null ) {
  679. return;
  680. }
  681. if ( typeof defaultHandler !== 'function' ) {
  682. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  683. }
  684. this.defaultHandler = defaultHandler;
  685. this.globalMessageManager.addMessageListener(
  686. location.host + ':background',
  687. this.onMessage
  688. );
  689. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  690. vAPI.unload.push(function() {
  691. var gmm = vAPI.messaging.globalMessageManager;
  692. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  693. gmm.removeMessageListener(
  694. location.host + ':background',
  695. vAPI.messaging.onMessage
  696. );
  697. });
  698. };
  699. /******************************************************************************/
  700. vAPI.messaging.broadcast = function(message) {
  701. this.globalMessageManager.broadcastAsyncMessage(
  702. location.host + ':broadcast',
  703. JSON.stringify({broadcast: true, msg: message})
  704. );
  705. };
  706. /******************************************************************************/
  707. var httpObserver = {
  708. ABORT: Components.results.NS_BINDING_ABORTED,
  709. lastRequest: {
  710. url: null,
  711. type: null,
  712. tabId: null,
  713. frameId: null,
  714. parentFrameId: null
  715. },
  716. QueryInterface: (function() {
  717. var {XPCOMUtils} = Cu['import']('resource://gre/modules/XPCOMUtils.jsm', {});
  718. return XPCOMUtils.generateQI([
  719. Ci.nsIObserver,
  720. Ci.nsISupportsWeakReference
  721. ]);
  722. })(),
  723. register: function() {
  724. Services.obs.addObserver(httpObserver, 'http-on-opening-request', true);
  725. // Services.obs.addObserver(httpObserver, 'http-on-modify-request', true);
  726. Services.obs.addObserver(httpObserver, 'http-on-examine-response', true);
  727. },
  728. unregister: function() {
  729. Services.obs.removeObserver(httpObserver, 'http-on-opening-request');
  730. // Services.obs.removeObserver(httpObserver, 'http-on-modify-request');
  731. Services.obs.removeObserver(httpObserver, 'http-on-examine-response');
  732. },
  733. observe: function(httpChannel, topic) {
  734. // No need for QueryInterface if this check is performed?
  735. if ( !(httpChannel instanceof Ci.nsIHttpChannel) ) {
  736. return;
  737. }
  738. var URI = httpChannel.URI, tabId, result;
  739. if ( topic === 'http-on-modify-request' ) {
  740. // var onHeadersReceived = vAPI.net.onHeadersReceived;
  741. return;
  742. }
  743. if ( topic === 'http-on-examine-request' ) {
  744. try {
  745. tabId = httpChannel.getProperty('tabId');
  746. } catch (ex) {
  747. return;
  748. }
  749. if ( !tabId ) {
  750. return;
  751. }
  752. topic = 'Content-Security-Policy';
  753. try {
  754. result = httpChannel.getResponseHeader(topic);
  755. } catch (ex) {
  756. result = null;
  757. }
  758. result = vAPI.net.onHeadersReceived.callback({
  759. url: URI.spec,
  760. tabId: tabId,
  761. parentFrameId: -1,
  762. responseHeaders: result ? [{name: topic, value: result}] : []
  763. });
  764. if ( result ) {
  765. httpChannel.setResponseHeader(
  766. topic,
  767. result.responseHeaders.pop().value,
  768. true
  769. );
  770. }
  771. return;
  772. }
  773. // http-on-opening-request
  774. var lastRequest = this.lastRequest;
  775. if ( !lastRequest.url || lastRequest.url !== URI.spec ) {
  776. lastRequest.url = null;
  777. return;
  778. }
  779. // Important! When loading file via XHR for mirroring,
  780. // the URL will be the same, so it could fall into an infinite loop
  781. lastRequest.url = null;
  782. if ( lastRequest.type === 'main_frame'
  783. && httpChannel instanceof Ci.nsIWritablePropertyBag ) {
  784. httpChannel.setProperty('tabId', lastRequest.tabId);
  785. }
  786. var onBeforeRequest = vAPI.net.onBeforeRequest;
  787. if ( !onBeforeRequest.types.has(lastRequest.type) ) {
  788. return;
  789. }
  790. result = onBeforeRequest.callback({
  791. url: URI.spec,
  792. type: lastRequest.type,
  793. tabId: lastRequest.tabId,
  794. frameId: lastRequest.frameId,
  795. parentFrameId: lastRequest.parentFrameId
  796. });
  797. if ( !result || typeof result !== 'object' ) {
  798. return;
  799. }
  800. if ( result.cancel === true ) {
  801. httpChannel.cancel(this.ABORT);
  802. } else if ( result.redirectUrl ) {
  803. httpChannel.redirectionLimit = 1;
  804. httpChannel.redirectTo(
  805. Services.io.newURI(result.redirectUrl, null, null)
  806. );
  807. }
  808. }
  809. };
  810. /******************************************************************************/
  811. vAPI.net = {};
  812. /******************************************************************************/
  813. vAPI.net.registerListeners = function() {
  814. var typeMap = {
  815. 2: 'script',
  816. 3: 'image',
  817. 4: 'stylesheet',
  818. 5: 'object',
  819. 6: 'main_frame',
  820. 7: 'sub_frame',
  821. 11: 'xmlhttprequest'
  822. };
  823. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  824. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  825. var shouldLoadListener = function(e) {
  826. var lastRequest = httpObserver.lastRequest;
  827. lastRequest.url = e.data.url;
  828. lastRequest.type = typeMap[e.data.type] || 'other';
  829. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  830. lastRequest.frameId = e.data.frameId;
  831. lastRequest.parentFrameId = e.data.parentFrameId;
  832. };
  833. vAPI.messaging.globalMessageManager.addMessageListener(
  834. shouldLoadListenerMessageName,
  835. shouldLoadListener
  836. );
  837. httpObserver.register();
  838. vAPI.unload.push(function() {
  839. vAPI.messaging.globalMessageManager.removeMessageListener(
  840. shouldLoadListenerMessageName,
  841. shouldLoadListener
  842. );
  843. httpObserver.unregister();
  844. });
  845. };
  846. /******************************************************************************/
  847. vAPI.contextMenu = {
  848. contextMap: {
  849. frame: 'inFrame',
  850. link: 'onLink',
  851. image: 'onImage',
  852. audio: 'onAudio',
  853. video: 'onVideo',
  854. editable: 'onEditableArea'
  855. }
  856. };
  857. /******************************************************************************/
  858. vAPI.contextMenu.displayMenuItem = function(e) {
  859. var doc = e.target.ownerDocument;
  860. var gContextMenu = doc.defaultView.gContextMenu;
  861. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  862. if ( /^https?$/.test(gContextMenu.browser.currentURI.scheme) === false) {
  863. menuitem.hidden = true;
  864. return;
  865. }
  866. var ctx = vAPI.contextMenu.contexts;
  867. if ( !ctx ) {
  868. menuitem.hidden = false;
  869. return;
  870. }
  871. var ctxMap = vAPI.contextMenu.contextMap;
  872. for ( var context of ctx ) {
  873. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  874. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  875. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  876. menuitem.hidden = false;
  877. return;
  878. }
  879. if ( gContextMenu[ctxMap[context]] ) {
  880. menuitem.hidden = false;
  881. return;
  882. }
  883. }
  884. menuitem.hidden = true;
  885. };
  886. /******************************************************************************/
  887. vAPI.contextMenu.register = function(doc) {
  888. if ( !this.menuItemId ) {
  889. return;
  890. }
  891. var contextMenu = doc.getElementById('contentAreaContextMenu');
  892. var menuitem = doc.createElement('menuitem');
  893. menuitem.setAttribute('id', this.menuItemId);
  894. menuitem.setAttribute('label', this.menuLabel);
  895. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  896. menuitem.setAttribute('class', 'menuitem-iconic');
  897. menuitem.addEventListener('command', this.onCommand);
  898. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  899. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  900. };
  901. /******************************************************************************/
  902. vAPI.contextMenu.unregister = function(doc) {
  903. if ( !this.menuItemId ) {
  904. return;
  905. }
  906. var menuitem = doc.getElementById(this.menuItemId);
  907. var contextMenu = menuitem.parentNode;
  908. menuitem.removeEventListener('command', this.onCommand);
  909. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  910. contextMenu.removeChild(menuitem);
  911. };
  912. /******************************************************************************/
  913. vAPI.contextMenu.create = function(details, callback) {
  914. this.menuItemId = details.id;
  915. this.menuLabel = details.title;
  916. this.contexts = details.contexts;
  917. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  918. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  919. } else {
  920. // default in Chrome
  921. this.contexts = ['page'];
  922. }
  923. this.onCommand = function() {
  924. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  925. var details = {
  926. menuItemId: this.id,
  927. tagName: gContextMenu.target.tagName.toLowerCase()
  928. };
  929. if ( gContextMenu.inFrame ) {
  930. details.frameUrl = gContextMenu.focusedWindow.location.href;
  931. } else if ( gContextMenu.onImage || gContextMenu.onAudio || gContextMenu.onVideo ) {
  932. details.srcUrl = gContextMenu.mediaURL;
  933. } else if ( gContextMenu.onLink ) {
  934. details.linkUrl = gContextMenu.linkURL;
  935. }
  936. callback(details, {
  937. id: vAPI.tabs.getTabId(gContextMenu.browser),
  938. url: gContextMenu.browser.currentURI.spec
  939. });
  940. };
  941. for ( var win of vAPI.tabs.getWindows() ) {
  942. this.register(win.document);
  943. }
  944. };
  945. /******************************************************************************/
  946. vAPI.contextMenu.remove = function() {
  947. for ( var win of vAPI.tabs.getWindows() ) {
  948. this.unregister(win.document);
  949. }
  950. this.menuItemId = null;
  951. this.menuLabel = null;
  952. this.contexts = null;
  953. this.onCommand = null;
  954. };
  955. /******************************************************************************/
  956. vAPI.lastError = function() {
  957. return null;
  958. };
  959. /******************************************************************************/
  960. // This is called only once, when everything has been loaded in memory after
  961. // the extension was launched. It can be used to inject content scripts
  962. // in already opened web pages, to remove whatever nuisance could make it to
  963. // the web pages before uBlock was ready.
  964. vAPI.onLoadAllCompleted = function() {};
  965. /******************************************************************************/
  966. // clean up when the extension is disabled
  967. window.addEventListener('unload', function() {
  968. for ( var unload of vAPI.unload ) {
  969. unload();
  970. }
  971. // frameModule needs to be cleared too
  972. var frameModule = {};
  973. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  974. frameModule.contentPolicy.unregister();
  975. frameModule.docObserver.unregister();
  976. Cu.unload(vAPI.getURL('frameModule.js'));
  977. });
  978. /******************************************************************************/
  979. })();
  980. /******************************************************************************/