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.

913 lines
26 KiB

  1. /*******************************************************************************
  2. µBlock - a Chromium 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. vAPI.app = {
  30. name: 'µBlock',
  31. version: '0.7.2.0',
  32. cleanName: location.host
  33. };
  34. /******************************************************************************/
  35. vAPI.app.restart = function() {};
  36. /******************************************************************************/
  37. // list of things that needs to be destroyed when disabling the extension
  38. vAPI.unload = [];
  39. /******************************************************************************/
  40. var SQLite = {
  41. open: function() {
  42. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  43. path.append('extension-data');
  44. if (!path.exists()) {
  45. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  46. }
  47. if (!path.isDirectory()) {
  48. throw Error('Should be a directory...');
  49. }
  50. path.append(vAPI.app.cleanName + '.sqlite');
  51. this.db = Services.storage.openDatabase(path);
  52. this.db.executeSimpleSQL(
  53. 'CREATE TABLE IF NOT EXISTS settings' +
  54. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  55. );
  56. vAPI.unload.push(function() {
  57. SQLite.run('VACUUM');
  58. SQLite.db.asyncClose();
  59. });
  60. },
  61. run: function(query, values, callback) {
  62. if (!this.db) {
  63. this.open();
  64. }
  65. var result = {};
  66. query = this.db.createAsyncStatement(query);
  67. if (Array.isArray(values) && values.length) {
  68. var i = values.length;
  69. while (i--) {
  70. query.bindByIndex(i, values[i]);
  71. }
  72. }
  73. query.executeAsync({
  74. handleResult: function(rows) {
  75. if (!rows || typeof callback !== 'function') {
  76. return;
  77. }
  78. var row;
  79. while (row = rows.getNextRow()) {
  80. // we assume that there will be two columns, since we're
  81. // using it only for preferences
  82. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  83. }
  84. },
  85. handleCompletion: function(reason) {
  86. if (typeof callback === 'function' && reason === 0) {
  87. callback(result);
  88. }
  89. },
  90. handleError: function(error) {
  91. console.error('SQLite error ', error.result, error.message);
  92. }
  93. });
  94. }
  95. };
  96. /******************************************************************************/
  97. vAPI.storage = {
  98. QUOTA_BYTES: 100 * 1024 * 1024,
  99. sqlWhere: function(col, params) {
  100. if (params > 0) {
  101. params = Array(params + 1).join('?, ').slice(0, -2);
  102. return ' WHERE ' + col + ' IN (' + params + ')';
  103. }
  104. return '';
  105. },
  106. get: function(details, callback) {
  107. if (typeof callback !== 'function') {
  108. return;
  109. }
  110. var values = [], defaults = false;
  111. if (details !== null) {
  112. if (Array.isArray(details)) {
  113. values = details;
  114. }
  115. else if (typeof details === 'object') {
  116. defaults = true;
  117. values = Object.keys(details);
  118. }
  119. else {
  120. values = [details.toString()];
  121. }
  122. }
  123. SQLite.run(
  124. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  125. values,
  126. function(result) {
  127. var key;
  128. for (key in result) {
  129. result[key] = JSON.parse(result[key]);
  130. }
  131. if (defaults) {
  132. for (key in details) {
  133. if (!result[key]) {
  134. result[key] = details[key];
  135. }
  136. }
  137. }
  138. callback(result);
  139. }
  140. );
  141. },
  142. set: function(details, callback) {
  143. var key, values = [], placeholders = [];
  144. for (key in details) {
  145. values.push(key);
  146. values.push(JSON.stringify(details[key]));
  147. placeholders.push('?, ?');
  148. }
  149. if (!values.length) {
  150. return;
  151. }
  152. SQLite.run(
  153. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  154. placeholders.join(' UNION SELECT '),
  155. values,
  156. callback
  157. );
  158. },
  159. remove: function(keys, callback) {
  160. if (typeof keys === 'string') {
  161. keys = [keys];
  162. }
  163. SQLite.run(
  164. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  165. keys,
  166. callback
  167. );
  168. },
  169. clear: function(callback) {
  170. SQLite.run('DELETE FROM settings', null, callback);
  171. SQLite.run('VACUUM');
  172. },
  173. getBytesInUse: function(keys, callback) {
  174. if (typeof callback !== 'function') {
  175. return;
  176. }
  177. SQLite.run(
  178. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  179. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  180. keys,
  181. function(result) {
  182. callback(result.size);
  183. }
  184. );
  185. }
  186. };
  187. /******************************************************************************/
  188. var windowWatcher = {
  189. onTabClose: function(e) {
  190. var tabId = vAPI.tabs.getTabId(e.target);
  191. vAPI.tabs.onClosed(tabId);
  192. delete vAPI.tabIcons[tabId];
  193. },
  194. onTabSelect: function(e) {
  195. vAPI.setIcon(
  196. vAPI.tabs.getTabId(e.target),
  197. e.target.ownerDocument.defaultView
  198. );
  199. },
  200. onLoad: function(e) {
  201. if (e) {
  202. this.removeEventListener('load', windowWatcher.onLoad);
  203. }
  204. var docElement = this.document.documentElement;
  205. if (docElement.getAttribute('windowtype') !== 'navigator:browser') {
  206. return;
  207. }
  208. if (!this.gBrowser || !this.gBrowser.tabContainer) {
  209. return;
  210. }
  211. var tC = this.gBrowser.tabContainer;
  212. this.gBrowser.addTabsProgressListener(tabsProgressListener);
  213. tC.addEventListener('TabClose', windowWatcher.onTabClose);
  214. tC.addEventListener('TabSelect', windowWatcher.onTabSelect);
  215. vAPI.toolbarButton.add(this.document);
  216. // when new window is opened TabSelect doesn't run on the selected tab?
  217. },
  218. observe: function(win, topic) {
  219. if (topic === 'domwindowopened') {
  220. win.addEventListener('load', this.onLoad);
  221. }
  222. }
  223. };
  224. /******************************************************************************/
  225. var tabsProgressListener = {
  226. onLocationChange: function(browser, webProgress, request, location, flags) {
  227. if (!webProgress.isTopLevel) {
  228. return;
  229. }
  230. var tabId = vAPI.tabs.getTabId(browser);
  231. if (flags & 1) {
  232. vAPI.tabs.onUpdated(tabId, {url: location.spec}, {
  233. frameId: 0,
  234. tabId: tabId,
  235. url: browser.currentURI.spec
  236. });
  237. }
  238. else {
  239. vAPI.tabs.onNavigation({
  240. frameId: 0,
  241. tabId: tabId,
  242. url: location.spec
  243. });
  244. }
  245. }
  246. };
  247. /******************************************************************************/
  248. vAPI.tabs = {};
  249. /******************************************************************************/
  250. vAPI.tabs.registerListeners = function() {
  251. // onNavigation and onUpdated handled with tabsProgressListener
  252. // onClosed - handled in windowWatcher.onTabClose
  253. // onPopup ?
  254. Services.ww.registerNotification(windowWatcher);
  255. for (var win of this.getWindows()) {
  256. windowWatcher.onLoad.call(win);
  257. }
  258. vAPI.toolbarButton.init();
  259. vAPI.unload.push(function() {
  260. Services.ww.unregisterNotification(windowWatcher);
  261. for (var win of vAPI.tabs.getWindows()) {
  262. vAPI.toolbarButton.remove(win.document);
  263. win.removeEventListener('load', windowWatcher.onLoad);
  264. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  265. var tC = win.gBrowser.tabContainer;
  266. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  267. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  268. // close extension tabs
  269. for (var tab of win.gBrowser.tabs) {
  270. var URI = tab.linkedBrowser.currentURI;
  271. if (URI.scheme === 'chrome' && URI.host === vAPI.app.cleanName) {
  272. win.gBrowser.removeTab(tab);
  273. }
  274. }
  275. }
  276. });
  277. };
  278. /******************************************************************************/
  279. vAPI.tabs.getTabId = function(target) {
  280. if (target.linkedPanel) {
  281. return target.linkedPanel.slice(6);
  282. }
  283. var gBrowser = target.ownerDocument.defaultView.gBrowser;
  284. var i = gBrowser.browsers.indexOf(target);
  285. if (i !== -1) {
  286. i = gBrowser.tabs[i].linkedPanel.slice(6);
  287. }
  288. return i;
  289. };
  290. /******************************************************************************/
  291. vAPI.tabs.get = function(tabId, callback) {
  292. var tab, windows;
  293. if (tabId === null) {
  294. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  295. tabId = vAPI.tabs.getTabId(tab);
  296. }
  297. else {
  298. windows = this.getWindows();
  299. for (var win of windows) {
  300. tab = win.gBrowser.tabContainer.querySelector(
  301. 'tab[linkedpanel="panel-' + tabId + '"]'
  302. );
  303. if (tab) {
  304. break;
  305. }
  306. }
  307. }
  308. if (!tab) {
  309. callback();
  310. return;
  311. }
  312. var browser = tab.linkedBrowser;
  313. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  314. if (!windows) {
  315. windows = this.getWindows();
  316. }
  317. callback({
  318. id: tabId,
  319. index: gBrowser.browsers.indexOf(browser),
  320. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  321. active: tab === gBrowser.selectedTab,
  322. url: browser.currentURI.spec,
  323. title: tab.label
  324. });
  325. };
  326. /******************************************************************************/
  327. vAPI.tabs.getAll = function(window) {
  328. var tabs = [];
  329. for (var win of this.getWindows()) {
  330. if (window && window !== win) {
  331. continue;
  332. }
  333. for (var tab of win.gBrowser.tabs) {
  334. tabs.push(tab);
  335. }
  336. }
  337. return tabs;
  338. };
  339. /******************************************************************************/
  340. vAPI.tabs.getWindows = function() {
  341. var winumerator = Services.wm.getEnumerator('navigator:browser');
  342. var windows = [];
  343. while (winumerator.hasMoreElements()) {
  344. var win = winumerator.getNext();
  345. if (!win.closed) {
  346. windows.push(win);
  347. }
  348. }
  349. return windows;
  350. };
  351. /******************************************************************************/
  352. // properties of the details object:
  353. // url: 'URL', // the address that will be opened
  354. // tabId: 1, // the tab is used if set, instead of creating a new one
  355. // index: -1, // undefined: end of the list, -1: following tab, or after index
  356. // active: false, // opens the tab in background - true and undefined: foreground
  357. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  358. vAPI.tabs.open = function(details) {
  359. if (!details.url) {
  360. return null;
  361. }
  362. // extension pages
  363. if (!/^[\w-]{2,}:/.test(details.url)) {
  364. details.url = vAPI.getURL(details.url);
  365. }
  366. var tab, tabs;
  367. if (details.select) {
  368. var rgxHash = /#.*/;
  369. // this is questionable
  370. var url = details.url.replace(rgxHash, '');
  371. tabs = this.getAll();
  372. for (tab of tabs) {
  373. var browser = tab.linkedBrowser;
  374. if (browser.currentURI.spec.replace(rgxHash, '') === url) {
  375. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  376. return;
  377. }
  378. }
  379. }
  380. if (details.active === undefined) {
  381. details.active = true;
  382. }
  383. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  384. if (details.index === -1) {
  385. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  386. }
  387. if (details.tabId) {
  388. tabs = tabs || this.getAll();
  389. for (tab of tabs) {
  390. if (vAPI.tabs.getTabId(tab) === details.tabId) {
  391. tab.linkedBrowser.loadURI(details.url);
  392. return;
  393. }
  394. }
  395. }
  396. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  397. if (details.index !== undefined) {
  398. gBrowser.moveTabTo(tab, details.index);
  399. }
  400. };
  401. /******************************************************************************/
  402. vAPI.tabs.close = function(tabIds) {
  403. if (!Array.isArray(tabIds)) {
  404. tabIds = [tabIds];
  405. }
  406. tabIds = tabIds.map(function(tabId) {
  407. return 'tab[linkedpanel="panel-' + tabId + '"]';
  408. }).join(',');
  409. for (var win of this.getWindows()) {
  410. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  411. if (!tabs) {
  412. continue;
  413. }
  414. for (var tab of tabs) {
  415. win.gBrowser.removeTab(tab);
  416. }
  417. }
  418. };
  419. /******************************************************************************/
  420. vAPI.tabs.injectScript = function(tabId, details, callback) {
  421. };
  422. /******************************************************************************/
  423. vAPI.tabIcons = { /*tabId: {badge: 0, img: dict}*/ };
  424. vAPI.setIcon = function(tabId, img, badge) {
  425. var curWin = badge === undefined ? img : Services.wm.getMostRecentWindow('navigator:browser');
  426. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  427. // from 'TabSelect' event
  428. if (tabId === undefined) {
  429. tabId = curTabId;
  430. }
  431. else if (badge !== undefined) {
  432. vAPI.tabIcons[tabId] = {
  433. badge: badge === '>1K' ? '1k+' : badge,
  434. img: img && img[19] && img[19].replace(/19(-off)?\.png$/, '16$1.svg')
  435. };
  436. }
  437. if (tabId !== curTabId) {
  438. return;
  439. }
  440. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  441. var icon = vAPI.tabIcons[tabId];
  442. button.setAttribute('badge', icon && icon.badge || '');
  443. button.style.listStyleImage = 'url(' + vAPI.getURL(icon && icon.img || 'img/browsericons/icon16-off.svg') + ')';
  444. };
  445. /******************************************************************************/
  446. vAPI.toolbarButton = {
  447. widgetId: vAPI.app.cleanName + '-button',
  448. panelId: vAPI.app.cleanName + '-panel'
  449. };
  450. /******************************************************************************/
  451. vAPI.toolbarButton.init = function() {
  452. CustomizableUI.createWidget({
  453. id: this.widgetId,
  454. type: 'view',
  455. viewId: this.panelId,
  456. defaultArea: CustomizableUI.AREA_NAVBAR,
  457. label: vAPI.app.name,
  458. tooltiptext: vAPI.app.name,
  459. onViewShowing: function(e) {
  460. e.target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  461. },
  462. onViewHiding: function(e) {
  463. e.target.firstChild.setAttribute('src', 'about:blank');
  464. }
  465. });
  466. var doc = Services.wm.getMostRecentWindow('navigator:browser').document;
  467. var button = doc.getElementById(this.widgetId);
  468. button.style.listStyleImage = 'url(' + vAPI.getURL('img/icon16.svg') + ')';
  469. if (!this.styleURI) {
  470. var css = encodeURIComponent([
  471. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  472. 'position: absolute; color: #fff; background: #666;',
  473. 'content: attr(badge); font-size: 9px; font-weight: bold;',
  474. 'padding: 1px 2px; margin-left: -16px; margin-top: 3px }'
  475. ].join(''));
  476. this.styleURI = Services.io.newURI('data:text/css,' + css, null, null);
  477. }
  478. var sss = Cc['@mozilla.org/content/style-sheet-service;1']
  479. .getService(Ci.nsIStyleSheetService);
  480. sss.loadAndRegisterSheet(this.styleURI, sss.USER_SHEET);
  481. vAPI.unload.push(function() {
  482. sss.unregisterSheet(this.styleURI, sss.USER_SHEET);
  483. CustomizableUI.createWidget(this.widgetId);
  484. }.bind(this));
  485. };
  486. /******************************************************************************/
  487. // it runs with windowWatcher when a window is opened
  488. // vAPI.tabs.registerListeners initializes it
  489. vAPI.toolbarButton.add = function(doc) {
  490. var panel = doc.createElement('panelview');
  491. panel.id = this.panelId;
  492. var iframe = panel.appendChild(doc.createElement('iframe'));
  493. iframe.setAttribute('type', 'content');
  494. panel.style.cssText = iframe.style.cssText
  495. = 'width: 180px; height: 310px; transition: width .1s, height .1s';
  496. doc.getElementById('PanelUI-multiView')
  497. .appendChild(panel)
  498. .appendChild(iframe);
  499. var updateTimer = null;
  500. var delayedResize = function() {
  501. if (updateTimer) {
  502. return;
  503. }
  504. updateTimer = setTimeout(resizePopup, 20);
  505. };
  506. var resizePopup = function() {
  507. var panelStyle = panel.style;
  508. var body = iframe.contentDocument.body;
  509. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  510. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  511. updateTimer = null;
  512. };
  513. var onPopupReady = function() {
  514. if (!this.contentWindow
  515. || this.contentWindow.location.host !== vAPI.app.cleanName) {
  516. return;
  517. }
  518. var mutObs = this.contentWindow.MutationObserver;
  519. (new mutObs(delayedResize)).observe(this.contentDocument, {
  520. childList: true,
  521. attributes: true,
  522. characterData: true,
  523. subtree: true
  524. });
  525. delayedResize();
  526. };
  527. iframe.addEventListener('load', onPopupReady, true);
  528. };
  529. /******************************************************************************/
  530. vAPI.toolbarButton.remove = function(doc) {
  531. var panel = doc.getElementById(this.panelId);
  532. panel.parentNode.removeChild(panel);
  533. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  534. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  535. };
  536. /******************************************************************************/
  537. vAPI.messaging = {
  538. get globalMessageManager() {
  539. return Cc['@mozilla.org/globalmessagemanager;1']
  540. .getService(Ci.nsIMessageListenerManager);
  541. },
  542. frameScript: vAPI.getURL('frameScript.js'),
  543. listeners: {},
  544. defaultHandler: null,
  545. NOOPFUNC: function(){},
  546. UNHANDLED: 'vAPI.messaging.notHandled'
  547. };
  548. /******************************************************************************/
  549. vAPI.messaging.listen = function(listenerName, callback) {
  550. this.listeners[listenerName] = callback;
  551. };
  552. /******************************************************************************/
  553. vAPI.messaging.onMessage = function(request) {
  554. var messageManager = request.target.messageManager;
  555. if (!messageManager) {
  556. // Message came from a popup, and its message manager is not usable.
  557. // So instead we broadcast to the parent window.
  558. messageManager = request.target
  559. .webNavigation.QueryInterface(Ci.nsIDocShell)
  560. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  561. }
  562. var listenerId = request.data.portName.split('|');
  563. var requestId = request.data.requestId;
  564. var portName = listenerId[1];
  565. listenerId = listenerId[0];
  566. var callback = vAPI.messaging.NOOPFUNC;
  567. if ( requestId !== undefined ) {
  568. callback = function(response) {
  569. var message = JSON.stringify({
  570. requestId: requestId,
  571. portName: portName,
  572. msg: response !== undefined ? response : null
  573. });
  574. if (messageManager.sendAsyncMessage) {
  575. messageManager.sendAsyncMessage(listenerId, message);
  576. }
  577. else {
  578. messageManager.broadcastAsyncMessage(listenerId, message);
  579. }
  580. };
  581. }
  582. var sender = {
  583. tab: {
  584. id: vAPI.tabs.getTabId(request.target)
  585. }
  586. };
  587. // Specific handler
  588. var r = vAPI.messaging.UNHANDLED;
  589. var listener = vAPI.messaging.listeners[portName];
  590. if ( typeof listener === 'function' ) {
  591. r = listener(request.data.msg, sender, callback);
  592. }
  593. if ( r !== vAPI.messaging.UNHANDLED ) {
  594. return;
  595. }
  596. // Default handler
  597. r = vAPI.messaging.defaultHandler(request.data.msg, sender, callback);
  598. if ( r !== vAPI.messaging.UNHANDLED ) {
  599. return;
  600. }
  601. console.error('µBlock> messaging > unknown request: %o', request.data);
  602. // Unhandled:
  603. // Need to callback anyways in case caller expected an answer, or
  604. // else there is a memory leak on caller's side
  605. callback();
  606. };
  607. /******************************************************************************/
  608. vAPI.messaging.setup = function(defaultHandler) {
  609. // Already setup?
  610. if ( this.defaultHandler !== null ) {
  611. return;
  612. }
  613. if ( typeof defaultHandler !== 'function' ) {
  614. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  615. }
  616. this.defaultHandler = defaultHandler;
  617. this.globalMessageManager.addMessageListener(
  618. vAPI.app.cleanName + ':background',
  619. this.onMessage
  620. );
  621. this.globalMessageManager.loadFrameScript(vAPI.messaging.frameScript, true);
  622. vAPI.unload.push(function() {
  623. var gmm = vAPI.messaging.globalMessageManager;
  624. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  625. gmm.removeMessageListener(
  626. vAPI.app.cleanName + ':background',
  627. vAPI.messaging.onMessage
  628. );
  629. });
  630. };
  631. /******************************************************************************/
  632. vAPI.messaging.broadcast = function(message) {
  633. this.globalMessageManager.broadcastAsyncMessage(
  634. vAPI.app.cleanName + ':broadcast',
  635. JSON.stringify({broadcast: true, msg: message})
  636. );
  637. };
  638. /******************************************************************************/
  639. vAPI.net = {
  640. beforeRequestMessageName: vAPI.app.cleanName + ':onBeforeRequest'
  641. };
  642. /******************************************************************************/
  643. vAPI.net.registerListeners = function() {
  644. var types = {
  645. 2: 'script',
  646. 3: 'image',
  647. 4: 'stylesheet',
  648. 5: 'object',
  649. 7: 'sub_frame',
  650. 11: 'xmlhttprequest'
  651. };
  652. var onBeforeRequest = this.onBeforeRequest;
  653. this.onBeforeRequest = function(e) {
  654. var details = e.data;
  655. details.type = types[details.type] || 'other';
  656. details.tabId = vAPI.tabs.getTabId(e.target);
  657. if (onBeforeRequest.types.indexOf(details.type) === -1) {
  658. return false;
  659. }
  660. var block = onBeforeRequest.callback(details);
  661. if (block && typeof block === 'object') {
  662. if (block.cancel === true) {
  663. return true;
  664. }
  665. else if (block.redirectURL) {
  666. return block.redirectURL;
  667. }
  668. }
  669. return false;
  670. };
  671. vAPI.messaging.globalMessageManager.addMessageListener(
  672. this.beforeRequestMessageName,
  673. this.onBeforeRequest
  674. );
  675. vAPI.unload.push(function() {
  676. vAPI.messaging.globalMessageManager.removeMessageListener(
  677. vAPI.net.beforeRequestMessageName,
  678. vAPI.net.onBeforeRequest
  679. );
  680. });
  681. };
  682. /******************************************************************************/
  683. vAPI.contextMenu = {};
  684. /******************************************************************************/
  685. vAPI.contextMenu.create = function(details, callback) {};
  686. /******************************************************************************/
  687. vAPI.contextMenu.remove = function() {};
  688. /******************************************************************************/
  689. vAPI.lastError = function() {
  690. return null;
  691. };
  692. /******************************************************************************/
  693. // clean up when the extension is disabled
  694. window.addEventListener('unload', function() {
  695. for (var unload of vAPI.unload) {
  696. unload();
  697. }
  698. // frameModule needs to be cleared too
  699. var frameModule = {};
  700. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  701. frameModule.contentPolicy.unregister();
  702. frameModule.docObserver.unregister();
  703. Cu.unload(vAPI.getURL('frameModule.js'));
  704. });
  705. /******************************************************************************/
  706. })();
  707. /******************************************************************************/