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.

1099 lines
31 KiB

  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.0'
  33. };
  34. /******************************************************************************/
  35. vAPI.app.restart = function() {};
  36. /******************************************************************************/
  37. // list of things that needs to be destroyed when disabling the extension
  38. // only functions should be added to it
  39. vAPI.unload = [];
  40. /******************************************************************************/
  41. var SQLite = {
  42. open: function() {
  43. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  44. path.append('extension-data');
  45. if (!path.exists()) {
  46. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  47. }
  48. if (!path.isDirectory()) {
  49. throw Error('Should be a directory...');
  50. }
  51. path.append(location.host + '.sqlite');
  52. this.db = Services.storage.openDatabase(path);
  53. this.db.executeSimpleSQL(
  54. 'CREATE TABLE IF NOT EXISTS settings' +
  55. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  56. );
  57. vAPI.unload.push(function() {
  58. // VACUUM somewhere else, instead on unload?
  59. SQLite.run('VACUUM');
  60. SQLite.db.asyncClose();
  61. });
  62. },
  63. run: function(query, values, callback) {
  64. if (!this.db) {
  65. this.open();
  66. }
  67. var result = {};
  68. query = this.db.createAsyncStatement(query);
  69. if (Array.isArray(values) && values.length) {
  70. var i = values.length;
  71. while (i--) {
  72. query.bindByIndex(i, values[i]);
  73. }
  74. }
  75. query.executeAsync({
  76. handleResult: function(rows) {
  77. if (!rows || typeof callback !== 'function') {
  78. return;
  79. }
  80. var row;
  81. while (row = rows.getNextRow()) {
  82. // we assume that there will be two columns, since we're
  83. // using it only for preferences
  84. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  85. }
  86. },
  87. handleCompletion: function(reason) {
  88. if (typeof callback === 'function' && reason === 0) {
  89. callback(result);
  90. }
  91. },
  92. handleError: function(error) {
  93. console.error('SQLite error ', error.result, error.message);
  94. }
  95. });
  96. }
  97. };
  98. /******************************************************************************/
  99. vAPI.storage = {
  100. QUOTA_BYTES: 100 * 1024 * 1024,
  101. sqlWhere: function(col, params) {
  102. if (params > 0) {
  103. params = Array(params + 1).join('?, ').slice(0, -2);
  104. return ' WHERE ' + col + ' IN (' + params + ')';
  105. }
  106. return '';
  107. },
  108. get: function(details, callback) {
  109. if (typeof callback !== 'function') {
  110. return;
  111. }
  112. var values = [], defaults = false;
  113. if (details !== null) {
  114. if (Array.isArray(details)) {
  115. values = details;
  116. }
  117. else if (typeof details === 'object') {
  118. defaults = true;
  119. values = Object.keys(details);
  120. }
  121. else {
  122. values = [details.toString()];
  123. }
  124. }
  125. SQLite.run(
  126. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  127. values,
  128. function(result) {
  129. var key;
  130. for (key in result) {
  131. result[key] = JSON.parse(result[key]);
  132. }
  133. if (defaults) {
  134. for (key in details) {
  135. if (!result[key]) {
  136. result[key] = details[key];
  137. }
  138. }
  139. }
  140. callback(result);
  141. }
  142. );
  143. },
  144. set: function(details, callback) {
  145. var key, values = [], placeholders = [];
  146. for (key in details) {
  147. values.push(key);
  148. values.push(JSON.stringify(details[key]));
  149. placeholders.push('?, ?');
  150. }
  151. if (!values.length) {
  152. return;
  153. }
  154. SQLite.run(
  155. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  156. placeholders.join(' UNION SELECT '),
  157. values,
  158. callback
  159. );
  160. },
  161. remove: function(keys, callback) {
  162. if (typeof keys === 'string') {
  163. keys = [keys];
  164. }
  165. SQLite.run(
  166. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  167. keys,
  168. callback
  169. );
  170. },
  171. clear: function(callback) {
  172. SQLite.run('DELETE FROM settings', null, callback);
  173. SQLite.run('VACUUM');
  174. },
  175. getBytesInUse: function(keys, callback) {
  176. if (typeof callback !== 'function') {
  177. return;
  178. }
  179. SQLite.run(
  180. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  181. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  182. keys,
  183. function(result) {
  184. callback(result.size);
  185. }
  186. );
  187. }
  188. };
  189. /******************************************************************************/
  190. var windowWatcher = {
  191. onTabClose: function(e) {
  192. var tabId = vAPI.tabs.getTabId(e.target);
  193. vAPI.tabs.onClosed(tabId);
  194. delete vAPI.tabIcons[tabId];
  195. },
  196. onTabSelect: function(e) {
  197. vAPI.setIcon(
  198. vAPI.tabs.getTabId(e.target),
  199. e.target.ownerDocument.defaultView
  200. );
  201. },
  202. onReady: function(e) {
  203. if (e) {
  204. this.removeEventListener(e.type, windowWatcher.onReady);
  205. }
  206. var wintype = this.document.documentElement.getAttribute('windowtype');
  207. if (wintype !== 'navigator:browser') {
  208. return;
  209. }
  210. if (!this.gBrowser || !this.gBrowser.tabContainer) {
  211. return;
  212. }
  213. var tC = this.gBrowser.tabContainer;
  214. this.gBrowser.addTabsProgressListener(tabsProgressListener);
  215. tC.addEventListener('TabClose', windowWatcher.onTabClose);
  216. tC.addEventListener('TabSelect', windowWatcher.onTabSelect);
  217. vAPI.toolbarButton.register(this.document);
  218. vAPI.contextMenu.register(this.document);
  219. // when new window is opened TabSelect doesn't run on the selected tab?
  220. },
  221. observe: function(win, topic) {
  222. if (topic === 'domwindowopened') {
  223. win.addEventListener('DOMContentLoaded', this.onReady);
  224. }
  225. }
  226. };
  227. /******************************************************************************/
  228. var tabsProgressListener = {
  229. onLocationChange: function(browser, webProgress, request, location, flags) {
  230. if (!webProgress.isTopLevel) {
  231. return;
  232. }
  233. var tabId = vAPI.tabs.getTabId(browser);
  234. if (flags & 1) {
  235. vAPI.tabs.onUpdated(tabId, {url: location.spec}, {
  236. frameId: 0,
  237. tabId: tabId,
  238. url: browser.currentURI.spec
  239. });
  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. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  267. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  268. var tC = win.gBrowser.tabContainer;
  269. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  270. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  271. // close extension tabs
  272. for (var tab of win.gBrowser.tabs) {
  273. var URI = tab.linkedBrowser.currentURI;
  274. if (URI.scheme === 'chrome' && URI.host === location.host) {
  275. win.gBrowser.removeTab(tab);
  276. }
  277. }
  278. }
  279. });
  280. };
  281. /******************************************************************************/
  282. vAPI.tabs.getTabId = function(target) {
  283. if (target.linkedPanel) {
  284. return target.linkedPanel.slice(6);
  285. }
  286. var i, gBrowser = target.ownerDocument.defaultView.gBrowser;
  287. // This should be more efficient from version 35
  288. if (gBrowser.getTabForBrowser) {
  289. i = gBrowser.getTabForBrowser(target);
  290. return i ? i.linkedPanel.slice(6) : -1;
  291. }
  292. i = gBrowser.browsers.indexOf(target);
  293. if (i !== -1) {
  294. i = gBrowser.tabs[i].linkedPanel.slice(6);
  295. }
  296. return i;
  297. };
  298. /******************************************************************************/
  299. vAPI.tabs.get = function(tabId, callback) {
  300. var tab, windows;
  301. if (tabId === null) {
  302. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  303. tabId = vAPI.tabs.getTabId(tab);
  304. }
  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 && callback === undefined) {
  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 tabs = [];
  341. for (var win of this.getWindows()) {
  342. if (window && window !== win) {
  343. continue;
  344. }
  345. for (var 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)) {
  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. tab.linkedBrowser.messageManager.sendAsyncMessage(
  438. location.host + ':broadcast',
  439. JSON.stringify({
  440. broadcast: true,
  441. portName: 'vAPI',
  442. msg: {
  443. cmd: 'injectScript',
  444. details: details
  445. }
  446. })
  447. );
  448. if (typeof callback === 'function') {
  449. setTimeout(callback, 13);
  450. }
  451. };
  452. /******************************************************************************/
  453. vAPI.tabIcons = { /*tabId: {badge: 0, img: dict}*/ };
  454. vAPI.setIcon = function(tabId, img, badge) {
  455. var curWin = badge === undefined ? img : Services.wm.getMostRecentWindow('navigator:browser');
  456. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  457. // from 'TabSelect' event
  458. if (tabId === undefined) {
  459. tabId = curTabId;
  460. }
  461. else if (badge !== undefined) {
  462. vAPI.tabIcons[tabId] = {
  463. badge: badge === '>1K' ? '1k+' : badge,
  464. img: img && img[19] && img[19].replace(/19(-off)?\.png$/, '16$1.svg')
  465. };
  466. }
  467. if (tabId !== curTabId) {
  468. return;
  469. }
  470. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  471. var icon = vAPI.tabIcons[tabId];
  472. button.setAttribute('badge', icon && icon.badge || '');
  473. icon = vAPI.getURL(icon && icon.img || 'img/browsericons/icon16-off.svg');
  474. button.style.listStyleImage = 'url(' + icon + ')';
  475. };
  476. /******************************************************************************/
  477. vAPI.toolbarButton = {
  478. widgetId: location.host + '-button',
  479. panelId: location.host + '-panel'
  480. };
  481. /******************************************************************************/
  482. vAPI.toolbarButton.init = function() {
  483. CustomizableUI.createWidget({
  484. id: this.widgetId,
  485. type: 'view',
  486. viewId: this.panelId,
  487. defaultArea: CustomizableUI.AREA_NAVBAR,
  488. label: vAPI.app.name,
  489. tooltiptext: vAPI.app.name,
  490. onViewShowing: function(e) {
  491. e.target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  492. },
  493. onViewHiding: function(e) {
  494. e.target.firstChild.setAttribute('src', 'about:blank');
  495. }
  496. });
  497. vAPI.unload.push(function() {
  498. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  499. });
  500. };
  501. /******************************************************************************/
  502. // it runs with windowWatcher when a window is opened
  503. // vAPI.tabs.registerListeners initializes it
  504. vAPI.toolbarButton.register = function(doc) {
  505. var panel = doc.createElement('panelview');
  506. panel.setAttribute('id', this.panelId);
  507. var iframe = panel.appendChild(doc.createElement('iframe'));
  508. iframe.setAttribute('type', 'content');
  509. panel.style.overflow = iframe.style.overflow = 'hidden';
  510. doc.getElementById('PanelUI-multiView')
  511. .appendChild(panel)
  512. .appendChild(iframe);
  513. var updateTimer = null;
  514. var delayedResize = function() {
  515. if (updateTimer) {
  516. return;
  517. }
  518. updateTimer = setTimeout(resizePopup, 20);
  519. };
  520. var resizePopup = function() {
  521. var panelStyle = panel.style;
  522. var body = iframe.contentDocument.body;
  523. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  524. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  525. updateTimer = null;
  526. };
  527. var onPopupReady = function() {
  528. if (!this.contentWindow
  529. || this.contentWindow.location.host !== location.host) {
  530. return;
  531. }
  532. var mutObs = this.contentWindow.MutationObserver;
  533. (new mutObs(delayedResize)).observe(this.contentDocument, {
  534. childList: true,
  535. attributes: true,
  536. characterData: true,
  537. subtree: true
  538. });
  539. delayedResize();
  540. };
  541. iframe.addEventListener('load', onPopupReady, true);
  542. if (!this.styleURI) {
  543. this.styleURI = 'data:text/css,' + encodeURIComponent([
  544. '#' + this.widgetId + ' {',
  545. 'list-style-image: url(',
  546. vAPI.getURL('img/browsericons/icon16-off.svg'),
  547. ');',
  548. '}',
  549. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  550. 'position: absolute;',
  551. 'margin-left: -16px;',
  552. 'margin-top: 3px;',
  553. 'padding: 1px 2px;',
  554. 'font-size: 9px;',
  555. 'font-weight: bold;',
  556. 'color: #fff;',
  557. 'background: #666;',
  558. 'content: attr(badge);',
  559. '}',
  560. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  561. 'width: 180px;',
  562. 'height: 310px;',
  563. 'transition: width .1s, height .1s;',
  564. '}'
  565. ].join(''));
  566. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  567. }
  568. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  569. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  570. };
  571. /******************************************************************************/
  572. vAPI.toolbarButton.unregister = function(doc) {
  573. var panel = doc.getElementById(this.panelId);
  574. panel.parentNode.removeChild(panel);
  575. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  576. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  577. };
  578. /******************************************************************************/
  579. vAPI.messaging = {
  580. get globalMessageManager() {
  581. return Cc['@mozilla.org/globalmessagemanager;1']
  582. .getService(Ci.nsIMessageListenerManager);
  583. },
  584. frameScript: vAPI.getURL('frameScript.js'),
  585. listeners: {},
  586. defaultHandler: null,
  587. NOOPFUNC: function(){},
  588. UNHANDLED: 'vAPI.messaging.notHandled'
  589. };
  590. /******************************************************************************/
  591. vAPI.messaging.listen = function(listenerName, callback) {
  592. this.listeners[listenerName] = callback;
  593. };
  594. /******************************************************************************/
  595. vAPI.messaging.onMessage = function(request) {
  596. var messageManager = request.target.messageManager;
  597. if (!messageManager) {
  598. // Message came from a popup, and its message manager is not usable.
  599. // So instead we broadcast to the parent window.
  600. messageManager = request.target
  601. .webNavigation.QueryInterface(Ci.nsIDocShell)
  602. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  603. }
  604. var listenerId = request.data.portName.split('|');
  605. var requestId = request.data.requestId;
  606. var portName = listenerId[1];
  607. listenerId = listenerId[0];
  608. var callback = vAPI.messaging.NOOPFUNC;
  609. if ( requestId !== undefined ) {
  610. callback = function(response) {
  611. var message = JSON.stringify({
  612. requestId: requestId,
  613. portName: portName,
  614. msg: response !== undefined ? response : null
  615. });
  616. if (messageManager.sendAsyncMessage) {
  617. messageManager.sendAsyncMessage(listenerId, message);
  618. }
  619. else {
  620. messageManager.broadcastAsyncMessage(listenerId, message);
  621. }
  622. };
  623. }
  624. var sender = {
  625. tab: {
  626. id: vAPI.tabs.getTabId(request.target)
  627. }
  628. };
  629. // Specific handler
  630. var r = vAPI.messaging.UNHANDLED;
  631. var listener = vAPI.messaging.listeners[portName];
  632. if ( typeof listener === 'function' ) {
  633. r = listener(request.data.msg, sender, callback);
  634. }
  635. if ( r !== vAPI.messaging.UNHANDLED ) {
  636. return;
  637. }
  638. // Default handler
  639. r = vAPI.messaging.defaultHandler(request.data.msg, sender, callback);
  640. if ( r !== vAPI.messaging.UNHANDLED ) {
  641. return;
  642. }
  643. console.error('µBlock> messaging > unknown request: %o', request.data);
  644. // Unhandled:
  645. // Need to callback anyways in case caller expected an answer, or
  646. // else there is a memory leak on caller's side
  647. callback();
  648. };
  649. /******************************************************************************/
  650. vAPI.messaging.setup = function(defaultHandler) {
  651. // Already setup?
  652. if ( this.defaultHandler !== null ) {
  653. return;
  654. }
  655. if ( typeof defaultHandler !== 'function' ) {
  656. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  657. }
  658. this.defaultHandler = defaultHandler;
  659. this.globalMessageManager.addMessageListener(
  660. location.host + ':background',
  661. this.onMessage
  662. );
  663. this.globalMessageManager.loadFrameScript(vAPI.messaging.frameScript, true);
  664. vAPI.unload.push(function() {
  665. var gmm = vAPI.messaging.globalMessageManager;
  666. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  667. gmm.removeMessageListener(
  668. location.host + ':background',
  669. vAPI.messaging.onMessage
  670. );
  671. });
  672. };
  673. /******************************************************************************/
  674. vAPI.messaging.broadcast = function(message) {
  675. this.globalMessageManager.broadcastAsyncMessage(
  676. location.host + ':broadcast',
  677. JSON.stringify({broadcast: true, msg: message})
  678. );
  679. };
  680. /******************************************************************************/
  681. vAPI.net = {
  682. beforeRequestMessageName: location.host + ':onBeforeRequest'
  683. };
  684. /******************************************************************************/
  685. vAPI.net.registerListeners = function() {
  686. var types = {
  687. 2: 'script',
  688. 3: 'image',
  689. 4: 'stylesheet',
  690. 5: 'object',
  691. 6: 'main_frame',
  692. 7: 'sub_frame',
  693. 11: 'xmlhttprequest'
  694. };
  695. var onBeforeRequest = this.onBeforeRequest;
  696. this.onBeforeRequest = function(e) {
  697. var details = e.data;
  698. details.type = types[details.type] || 'other';
  699. details.tabId = vAPI.tabs.getTabId(e.target);
  700. if (onBeforeRequest.types.indexOf(details.type) === -1) {
  701. return false;
  702. }
  703. var block = onBeforeRequest.callback(details);
  704. if (block && typeof block === 'object') {
  705. if (block.cancel === true) {
  706. return true;
  707. }
  708. else if (block.redirectURL) {
  709. return block.redirectURL;
  710. }
  711. }
  712. return false;
  713. };
  714. vAPI.messaging.globalMessageManager.addMessageListener(
  715. this.beforeRequestMessageName,
  716. this.onBeforeRequest
  717. );
  718. vAPI.unload.push(function() {
  719. vAPI.messaging.globalMessageManager.removeMessageListener(
  720. vAPI.net.beforeRequestMessageName,
  721. vAPI.net.onBeforeRequest
  722. );
  723. });
  724. };
  725. /******************************************************************************/
  726. vAPI.contextMenu = {
  727. contextMap: {
  728. frame: 'inFrame',
  729. link: 'onLink',
  730. image: 'onImage',
  731. audio: 'onAudio',
  732. video: 'onVideo',
  733. editable: 'onEditableArea'
  734. }
  735. };
  736. /******************************************************************************/
  737. vAPI.contextMenu.displayMenuItem = function(e) {
  738. var doc = e.target.ownerDocument;
  739. var gContextMenu = doc.defaultView.gContextMenu;
  740. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  741. if (!/^https?$/.test(gContextMenu.browser.currentURI.scheme)) {
  742. menuitem.hidden = true;
  743. return;
  744. }
  745. var ctx = vAPI.contextMenu.contexts;
  746. if (!ctx) {
  747. menuitem.hidden = false;
  748. return;
  749. }
  750. var ctxMap = vAPI.contextMenu.contextMap;
  751. for (var context of ctx) {
  752. if (context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  753. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  754. && !gContextMenu.onVideo && !gContextMenu.onAudio) {
  755. menuitem.hidden = false;
  756. return;
  757. }
  758. if (gContextMenu[ctxMap[context]]) {
  759. menuitem.hidden = false;
  760. return;
  761. }
  762. }
  763. menuitem.hidden = true;
  764. };
  765. /******************************************************************************/
  766. vAPI.contextMenu.register = function(doc) {
  767. if (!this.menuItemId) {
  768. return;
  769. }
  770. var contextMenu = doc.getElementById('contentAreaContextMenu');
  771. var menuitem = doc.createElement('menuitem');
  772. menuitem.setAttribute('id', this.menuItemId);
  773. menuitem.setAttribute('label', this.menuLabel);
  774. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  775. menuitem.setAttribute('class', 'menuitem-iconic');
  776. menuitem.addEventListener('command', this.onCommand);
  777. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  778. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  779. };
  780. /******************************************************************************/
  781. vAPI.contextMenu.unregister = function(doc) {
  782. if (!this.menuItemId) {
  783. return;
  784. }
  785. var menuitem = doc.getElementById(this.menuItemId);
  786. var contextMenu = menuitem.parentNode;
  787. menuitem.removeEventListener('command', this.onCommand);
  788. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  789. contextMenu.removeChild(menuitem);
  790. };
  791. /******************************************************************************/
  792. vAPI.contextMenu.create = function(details, callback) {
  793. this.menuItemId = details.id;
  794. this.menuLabel = details.title;
  795. this.contexts = details.contexts;
  796. if (Array.isArray(this.contexts) && this.contexts.length) {
  797. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  798. }
  799. else {
  800. // default in Chrome
  801. this.contexts = ['page'];
  802. }
  803. this.onCommand = function() {
  804. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  805. var details = {
  806. menuItemId: this.id,
  807. tagName: gContextMenu.target.tagName.toLowerCase()
  808. };
  809. if (gContextMenu.inFrame) {
  810. details.frameUrl = gContextMenu.focusedWindow.location.href;
  811. }
  812. else if (gContextMenu.onImage
  813. || gContextMenu.onAudio
  814. || gContextMenu.onVideo) {
  815. details.srcUrl = gContextMenu.mediaURL;
  816. }
  817. else if (gContextMenu.onLink) {
  818. details.linkUrl = gContextMenu.linkURL;
  819. }
  820. callback(details, {
  821. id: vAPI.tabs.getTabId(gContextMenu.browser),
  822. url: gContextMenu.browser.currentURI.spec
  823. });
  824. };
  825. for (var win of vAPI.tabs.getWindows()) {
  826. this.register(win.document);
  827. }
  828. };
  829. /******************************************************************************/
  830. vAPI.contextMenu.remove = function() {
  831. for (var win of vAPI.tabs.getWindows()) {
  832. this.unregister(win.document);
  833. }
  834. this.menuItemId = null;
  835. this.menuLabel = null;
  836. this.contexts = null;
  837. this.onCommand = null;
  838. };
  839. /******************************************************************************/
  840. vAPI.lastError = function() {
  841. return null;
  842. };
  843. /******************************************************************************/
  844. // This is called only once, when everything has been loaded in memory after
  845. // the extension was launched. It can be used to inject content scripts
  846. // in already opened web pages, to remove whatever nuisance could make it to
  847. // the web pages before uBlock was ready.
  848. vAPI.onLoadAllCompleted = function() {};
  849. /******************************************************************************/
  850. // clean up when the extension is disabled
  851. window.addEventListener('unload', function() {
  852. for (var unload of vAPI.unload) {
  853. unload();
  854. }
  855. // frameModule needs to be cleared too
  856. var frameModule = {};
  857. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  858. frameModule.contentPolicy.unregister();
  859. frameModule.docObserver.unregister();
  860. Cu.unload(vAPI.getURL('frameModule.js'));
  861. });
  862. /******************************************************************************/
  863. })();
  864. /******************************************************************************/