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.

1100 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] === undefined) {
  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');
  173. SQLite.run('VACUUM', null, callback);
  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. 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. }
  306. else {
  307. windows = this.getWindows();
  308. for (var win of windows) {
  309. tab = win.gBrowser.tabContainer.querySelector(
  310. 'tab[linkedpanel="panel-' + tabId + '"]'
  311. );
  312. if (tab) {
  313. break;
  314. }
  315. }
  316. }
  317. // for internal use
  318. if (tab && callback === undefined) {
  319. return tab;
  320. }
  321. if (!tab) {
  322. callback();
  323. return;
  324. }
  325. var browser = tab.linkedBrowser;
  326. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  327. if (!windows) {
  328. windows = this.getWindows();
  329. }
  330. callback({
  331. id: tabId,
  332. index: gBrowser.browsers.indexOf(browser),
  333. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  334. active: tab === gBrowser.selectedTab,
  335. url: browser.currentURI.spec,
  336. title: tab.label
  337. });
  338. };
  339. /******************************************************************************/
  340. vAPI.tabs.getAll = function(window) {
  341. var tabs = [];
  342. for (var win of this.getWindows()) {
  343. if (window && window !== win) {
  344. continue;
  345. }
  346. for (var tab of win.gBrowser.tabs) {
  347. tabs.push(tab);
  348. }
  349. }
  350. return tabs;
  351. };
  352. /******************************************************************************/
  353. vAPI.tabs.getWindows = function() {
  354. var winumerator = Services.wm.getEnumerator('navigator:browser');
  355. var windows = [];
  356. while (winumerator.hasMoreElements()) {
  357. var win = winumerator.getNext();
  358. if (!win.closed) {
  359. windows.push(win);
  360. }
  361. }
  362. return windows;
  363. };
  364. /******************************************************************************/
  365. // properties of the details object:
  366. // url: 'URL', // the address that will be opened
  367. // tabId: 1, // the tab is used if set, instead of creating a new one
  368. // index: -1, // undefined: end of the list, -1: following tab, or after index
  369. // active: false, // opens the tab in background - true and undefined: foreground
  370. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  371. vAPI.tabs.open = function(details) {
  372. if (!details.url) {
  373. return null;
  374. }
  375. // extension pages
  376. if (!/^[\w-]{2,}:/.test(details.url)) {
  377. details.url = vAPI.getURL(details.url);
  378. }
  379. var tab, tabs;
  380. if (details.select) {
  381. var rgxHash = /#.*/;
  382. // this is questionable
  383. var url = details.url.replace(rgxHash, '');
  384. tabs = this.getAll();
  385. for (tab of tabs) {
  386. var browser = tab.linkedBrowser;
  387. if (browser.currentURI.spec.replace(rgxHash, '') === url) {
  388. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  389. return;
  390. }
  391. }
  392. }
  393. if (details.active === undefined) {
  394. details.active = true;
  395. }
  396. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  397. if (details.index === -1) {
  398. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  399. }
  400. if (details.tabId) {
  401. tabs = tabs || this.getAll();
  402. for (tab of tabs) {
  403. if (vAPI.tabs.getTabId(tab) === details.tabId) {
  404. tab.linkedBrowser.loadURI(details.url);
  405. return;
  406. }
  407. }
  408. }
  409. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  410. if (details.index !== undefined) {
  411. gBrowser.moveTabTo(tab, details.index);
  412. }
  413. };
  414. /******************************************************************************/
  415. vAPI.tabs.close = function(tabIds) {
  416. if (!Array.isArray(tabIds)) {
  417. tabIds = [tabIds];
  418. }
  419. tabIds = tabIds.map(function(tabId) {
  420. return 'tab[linkedpanel="panel-' + tabId + '"]';
  421. }).join(',');
  422. for (var win of this.getWindows()) {
  423. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  424. if (!tabs) {
  425. continue;
  426. }
  427. for (var tab of tabs) {
  428. win.gBrowser.removeTab(tab);
  429. }
  430. }
  431. };
  432. /******************************************************************************/
  433. vAPI.tabs.injectScript = function(tabId, details, callback) {
  434. var tab = vAPI.tabs.get(tabId);
  435. if (!tab) {
  436. return;
  437. }
  438. tab.linkedBrowser.messageManager.sendAsyncMessage(
  439. location.host + ':broadcast',
  440. JSON.stringify({
  441. broadcast: true,
  442. portName: 'vAPI',
  443. msg: {
  444. cmd: 'injectScript',
  445. details: details
  446. }
  447. })
  448. );
  449. if (typeof callback === 'function') {
  450. setTimeout(callback, 13);
  451. }
  452. };
  453. /******************************************************************************/
  454. vAPI.tabIcons = { /*tabId: {badge: 0, img: dict}*/ };
  455. vAPI.setIcon = function(tabId, img, badge) {
  456. var curWin = badge === undefined ? img : Services.wm.getMostRecentWindow('navigator:browser');
  457. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  458. // from 'TabSelect' event
  459. if (tabId === undefined) {
  460. tabId = curTabId;
  461. }
  462. else if (badge !== undefined) {
  463. vAPI.tabIcons[tabId] = {
  464. badge: badge === '>1K' ? '1k+' : badge,
  465. img: img && img[19] && img[19].replace(/19(-off)?\.png$/, '16$1.svg')
  466. };
  467. }
  468. if (tabId !== curTabId) {
  469. return;
  470. }
  471. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  472. var icon = vAPI.tabIcons[tabId];
  473. button.setAttribute('badge', icon && icon.badge || '');
  474. icon = vAPI.getURL(icon && icon.img || 'img/browsericons/icon16-off.svg');
  475. button.style.listStyleImage = 'url(' + icon + ')';
  476. };
  477. /******************************************************************************/
  478. vAPI.toolbarButton = {
  479. widgetId: location.host + '-button',
  480. panelId: location.host + '-panel'
  481. };
  482. /******************************************************************************/
  483. vAPI.toolbarButton.init = function() {
  484. CustomizableUI.createWidget({
  485. id: this.widgetId,
  486. type: 'view',
  487. viewId: this.panelId,
  488. defaultArea: CustomizableUI.AREA_NAVBAR,
  489. label: vAPI.app.name,
  490. tooltiptext: vAPI.app.name,
  491. onViewShowing: function(e) {
  492. e.target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  493. },
  494. onViewHiding: function(e) {
  495. e.target.firstChild.setAttribute('src', 'about:blank');
  496. }
  497. });
  498. vAPI.unload.push(function() {
  499. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  500. });
  501. };
  502. /******************************************************************************/
  503. // it runs with windowWatcher when a window is opened
  504. // vAPI.tabs.registerListeners initializes it
  505. vAPI.toolbarButton.register = function(doc) {
  506. var panel = doc.createElement('panelview');
  507. panel.setAttribute('id', this.panelId);
  508. var iframe = panel.appendChild(doc.createElement('iframe'));
  509. iframe.setAttribute('type', 'content');
  510. panel.style.overflow = iframe.style.overflow = 'hidden';
  511. doc.getElementById('PanelUI-multiView')
  512. .appendChild(panel)
  513. .appendChild(iframe);
  514. var updateTimer = null;
  515. var delayedResize = function() {
  516. if (updateTimer) {
  517. return;
  518. }
  519. updateTimer = setTimeout(resizePopup, 20);
  520. };
  521. var resizePopup = function() {
  522. var panelStyle = panel.style;
  523. var body = iframe.contentDocument.body;
  524. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  525. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  526. updateTimer = null;
  527. };
  528. var onPopupReady = function() {
  529. if (!this.contentWindow
  530. || this.contentWindow.location.host !== location.host) {
  531. return;
  532. }
  533. var mutObs = this.contentWindow.MutationObserver;
  534. (new mutObs(delayedResize)).observe(this.contentDocument, {
  535. childList: true,
  536. attributes: true,
  537. characterData: true,
  538. subtree: true
  539. });
  540. delayedResize();
  541. };
  542. iframe.addEventListener('load', onPopupReady, true);
  543. if (!this.styleURI) {
  544. this.styleURI = 'data:text/css,' + encodeURIComponent([
  545. '#' + this.widgetId + ' {',
  546. 'list-style-image: url(',
  547. vAPI.getURL('img/browsericons/icon16-off.svg'),
  548. ');',
  549. '}',
  550. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  551. 'position: absolute;',
  552. 'margin-left: -16px;',
  553. 'margin-top: 3px;',
  554. 'padding: 1px 2px;',
  555. 'font-size: 9px;',
  556. 'font-weight: bold;',
  557. 'color: #fff;',
  558. 'background: #666;',
  559. 'content: attr(badge);',
  560. '}',
  561. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  562. 'width: 180px;',
  563. 'height: 310px;',
  564. 'transition: width .1s, height .1s;',
  565. '}'
  566. ].join(''));
  567. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  568. }
  569. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  570. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  571. };
  572. /******************************************************************************/
  573. vAPI.toolbarButton.unregister = function(doc) {
  574. var panel = doc.getElementById(this.panelId);
  575. panel.parentNode.removeChild(panel);
  576. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  577. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  578. };
  579. /******************************************************************************/
  580. vAPI.messaging = {
  581. get globalMessageManager() {
  582. return Cc['@mozilla.org/globalmessagemanager;1']
  583. .getService(Ci.nsIMessageListenerManager);
  584. },
  585. frameScript: vAPI.getURL('frameScript.js'),
  586. listeners: {},
  587. defaultHandler: null,
  588. NOOPFUNC: function(){},
  589. UNHANDLED: 'vAPI.messaging.notHandled'
  590. };
  591. /******************************************************************************/
  592. vAPI.messaging.listen = function(listenerName, callback) {
  593. this.listeners[listenerName] = callback;
  594. };
  595. /******************************************************************************/
  596. vAPI.messaging.onMessage = function(request) {
  597. var messageManager = request.target.messageManager;
  598. if (!messageManager) {
  599. // Message came from a popup, and its message manager is not usable.
  600. // So instead we broadcast to the parent window.
  601. messageManager = request.target
  602. .webNavigation.QueryInterface(Ci.nsIDocShell)
  603. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  604. }
  605. var listenerId = request.data.portName.split('|');
  606. var requestId = request.data.requestId;
  607. var portName = listenerId[1];
  608. listenerId = listenerId[0];
  609. var callback = vAPI.messaging.NOOPFUNC;
  610. if ( requestId !== undefined ) {
  611. callback = function(response) {
  612. var message = JSON.stringify({
  613. requestId: requestId,
  614. portName: portName,
  615. msg: response !== undefined ? response : null
  616. });
  617. if (messageManager.sendAsyncMessage) {
  618. messageManager.sendAsyncMessage(listenerId, message);
  619. }
  620. else {
  621. messageManager.broadcastAsyncMessage(listenerId, message);
  622. }
  623. };
  624. }
  625. var sender = {
  626. tab: {
  627. id: vAPI.tabs.getTabId(request.target)
  628. }
  629. };
  630. // Specific handler
  631. var r = vAPI.messaging.UNHANDLED;
  632. var listener = vAPI.messaging.listeners[portName];
  633. if ( typeof listener === 'function' ) {
  634. r = listener(request.data.msg, sender, callback);
  635. }
  636. if ( r !== vAPI.messaging.UNHANDLED ) {
  637. return;
  638. }
  639. // Default handler
  640. r = vAPI.messaging.defaultHandler(request.data.msg, sender, callback);
  641. if ( r !== vAPI.messaging.UNHANDLED ) {
  642. return;
  643. }
  644. console.error('µBlock> messaging > unknown request: %o', request.data);
  645. // Unhandled:
  646. // Need to callback anyways in case caller expected an answer, or
  647. // else there is a memory leak on caller's side
  648. callback();
  649. };
  650. /******************************************************************************/
  651. vAPI.messaging.setup = function(defaultHandler) {
  652. // Already setup?
  653. if ( this.defaultHandler !== null ) {
  654. return;
  655. }
  656. if ( typeof defaultHandler !== 'function' ) {
  657. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  658. }
  659. this.defaultHandler = defaultHandler;
  660. this.globalMessageManager.addMessageListener(
  661. location.host + ':background',
  662. this.onMessage
  663. );
  664. this.globalMessageManager.loadFrameScript(vAPI.messaging.frameScript, true);
  665. vAPI.unload.push(function() {
  666. var gmm = vAPI.messaging.globalMessageManager;
  667. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  668. gmm.removeMessageListener(
  669. location.host + ':background',
  670. vAPI.messaging.onMessage
  671. );
  672. });
  673. };
  674. /******************************************************************************/
  675. vAPI.messaging.broadcast = function(message) {
  676. this.globalMessageManager.broadcastAsyncMessage(
  677. location.host + ':broadcast',
  678. JSON.stringify({broadcast: true, msg: message})
  679. );
  680. };
  681. /******************************************************************************/
  682. vAPI.net = {
  683. beforeRequestMessageName: location.host + ':onBeforeRequest'
  684. };
  685. /******************************************************************************/
  686. vAPI.net.registerListeners = function() {
  687. var types = {
  688. 2: 'script',
  689. 3: 'image',
  690. 4: 'stylesheet',
  691. 5: 'object',
  692. 6: 'main_frame',
  693. 7: 'sub_frame',
  694. 11: 'xmlhttprequest'
  695. };
  696. var onBeforeRequest = this.onBeforeRequest;
  697. this.onBeforeRequest = function(e) {
  698. var details = e.data;
  699. details.type = types[details.type] || 'other';
  700. details.tabId = vAPI.tabs.getTabId(e.target);
  701. if (onBeforeRequest.types.indexOf(details.type) === -1) {
  702. return false;
  703. }
  704. var block = onBeforeRequest.callback(details);
  705. if (block && typeof block === 'object') {
  706. if (block.cancel === true) {
  707. return true;
  708. }
  709. else if (block.redirectURL) {
  710. return block.redirectURL;
  711. }
  712. }
  713. return false;
  714. };
  715. vAPI.messaging.globalMessageManager.addMessageListener(
  716. this.beforeRequestMessageName,
  717. this.onBeforeRequest
  718. );
  719. vAPI.unload.push(function() {
  720. vAPI.messaging.globalMessageManager.removeMessageListener(
  721. vAPI.net.beforeRequestMessageName,
  722. vAPI.net.onBeforeRequest
  723. );
  724. });
  725. };
  726. /******************************************************************************/
  727. vAPI.contextMenu = {
  728. contextMap: {
  729. frame: 'inFrame',
  730. link: 'onLink',
  731. image: 'onImage',
  732. audio: 'onAudio',
  733. video: 'onVideo',
  734. editable: 'onEditableArea'
  735. }
  736. };
  737. /******************************************************************************/
  738. vAPI.contextMenu.displayMenuItem = function(e) {
  739. var doc = e.target.ownerDocument;
  740. var gContextMenu = doc.defaultView.gContextMenu;
  741. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  742. if (!/^https?$/.test(gContextMenu.browser.currentURI.scheme)) {
  743. menuitem.hidden = true;
  744. return;
  745. }
  746. var ctx = vAPI.contextMenu.contexts;
  747. if (!ctx) {
  748. menuitem.hidden = false;
  749. return;
  750. }
  751. var ctxMap = vAPI.contextMenu.contextMap;
  752. for (var context of ctx) {
  753. if (context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  754. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  755. && !gContextMenu.onVideo && !gContextMenu.onAudio) {
  756. menuitem.hidden = false;
  757. return;
  758. }
  759. if (gContextMenu[ctxMap[context]]) {
  760. menuitem.hidden = false;
  761. return;
  762. }
  763. }
  764. menuitem.hidden = true;
  765. };
  766. /******************************************************************************/
  767. vAPI.contextMenu.register = function(doc) {
  768. if (!this.menuItemId) {
  769. return;
  770. }
  771. var contextMenu = doc.getElementById('contentAreaContextMenu');
  772. var menuitem = doc.createElement('menuitem');
  773. menuitem.setAttribute('id', this.menuItemId);
  774. menuitem.setAttribute('label', this.menuLabel);
  775. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  776. menuitem.setAttribute('class', 'menuitem-iconic');
  777. menuitem.addEventListener('command', this.onCommand);
  778. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  779. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  780. };
  781. /******************************************************************************/
  782. vAPI.contextMenu.unregister = function(doc) {
  783. if (!this.menuItemId) {
  784. return;
  785. }
  786. var menuitem = doc.getElementById(this.menuItemId);
  787. var contextMenu = menuitem.parentNode;
  788. menuitem.removeEventListener('command', this.onCommand);
  789. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  790. contextMenu.removeChild(menuitem);
  791. };
  792. /******************************************************************************/
  793. vAPI.contextMenu.create = function(details, callback) {
  794. this.menuItemId = details.id;
  795. this.menuLabel = details.title;
  796. this.contexts = details.contexts;
  797. if (Array.isArray(this.contexts) && this.contexts.length) {
  798. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  799. }
  800. else {
  801. // default in Chrome
  802. this.contexts = ['page'];
  803. }
  804. this.onCommand = function() {
  805. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  806. var details = {
  807. menuItemId: this.id,
  808. tagName: gContextMenu.target.tagName.toLowerCase()
  809. };
  810. if (gContextMenu.inFrame) {
  811. details.frameUrl = gContextMenu.focusedWindow.location.href;
  812. }
  813. else if (gContextMenu.onImage
  814. || gContextMenu.onAudio
  815. || gContextMenu.onVideo) {
  816. details.srcUrl = gContextMenu.mediaURL;
  817. }
  818. else if (gContextMenu.onLink) {
  819. details.linkUrl = gContextMenu.linkURL;
  820. }
  821. callback(details, {
  822. id: vAPI.tabs.getTabId(gContextMenu.browser),
  823. url: gContextMenu.browser.currentURI.spec
  824. });
  825. };
  826. for (var win of vAPI.tabs.getWindows()) {
  827. this.register(win.document);
  828. }
  829. };
  830. /******************************************************************************/
  831. vAPI.contextMenu.remove = function() {
  832. for (var win of vAPI.tabs.getWindows()) {
  833. this.unregister(win.document);
  834. }
  835. this.menuItemId = null;
  836. this.menuLabel = null;
  837. this.contexts = null;
  838. this.onCommand = null;
  839. };
  840. /******************************************************************************/
  841. vAPI.lastError = function() {
  842. return null;
  843. };
  844. /******************************************************************************/
  845. // This is called only once, when everything has been loaded in memory after
  846. // the extension was launched. It can be used to inject content scripts
  847. // in already opened web pages, to remove whatever nuisance could make it to
  848. // the web pages before uBlock was ready.
  849. vAPI.onLoadAllCompleted = function() {};
  850. /******************************************************************************/
  851. // clean up when the extension is disabled
  852. window.addEventListener('unload', function() {
  853. for (var unload of vAPI.unload) {
  854. unload();
  855. }
  856. // frameModule needs to be cleared too
  857. var frameModule = {};
  858. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  859. frameModule.contentPolicy.unregister();
  860. frameModule.docObserver.unregister();
  861. Cu.unload(vAPI.getURL('frameModule.js'));
  862. });
  863. /******************************************************************************/
  864. })();
  865. /******************************************************************************/