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.

917 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. onReady: function(e) {
  201. if (e) {
  202. this.removeEventListener(e.type, windowWatcher.onReady);
  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('DOMContentLoaded', this.onReady);
  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. for (var win of this.getWindows()) {
  255. windowWatcher.onReady.call(win);
  256. }
  257. Services.ww.registerNotification(windowWatcher);
  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.onReady);
  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. vAPI.unload.push(function() {
  467. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  468. });
  469. };
  470. /******************************************************************************/
  471. // it runs with windowWatcher when a window is opened
  472. // vAPI.tabs.registerListeners initializes it
  473. vAPI.toolbarButton.add = function(doc) {
  474. var panel = doc.createElement('panelview');
  475. panel.id = this.panelId;
  476. var iframe = panel.appendChild(doc.createElement('iframe'));
  477. iframe.setAttribute('type', 'content');
  478. panel.style.cssText = iframe.style.cssText
  479. = 'width: 180px; height: 310px; transition: width .1s, height .1s; overflow: hidden';
  480. doc.getElementById('PanelUI-multiView')
  481. .appendChild(panel)
  482. .appendChild(iframe);
  483. var updateTimer = null;
  484. var delayedResize = function() {
  485. if (updateTimer) {
  486. return;
  487. }
  488. updateTimer = setTimeout(resizePopup, 20);
  489. };
  490. var resizePopup = function() {
  491. var panelStyle = panel.style;
  492. var body = iframe.contentDocument.body;
  493. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  494. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  495. updateTimer = null;
  496. };
  497. var onPopupReady = function() {
  498. if (!this.contentWindow
  499. || this.contentWindow.location.host !== vAPI.app.cleanName) {
  500. return;
  501. }
  502. var mutObs = this.contentWindow.MutationObserver;
  503. (new mutObs(delayedResize)).observe(this.contentDocument, {
  504. childList: true,
  505. attributes: true,
  506. characterData: true,
  507. subtree: true
  508. });
  509. delayedResize();
  510. };
  511. iframe.addEventListener('load', onPopupReady, true);
  512. if (!this.styleURI) {
  513. this.styleURI = 'data:text/css,' + encodeURIComponent([
  514. '#' + this.widgetId + ' {',
  515. 'list-style-image: url(',
  516. vAPI.getURL('img/browsericons/icon16-off.svg'),
  517. ');',
  518. '}',
  519. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  520. 'position: absolute;',
  521. 'margin-left: -16px;',
  522. 'margin-top: 3px;',
  523. 'padding: 1px 2px;',
  524. 'font-size: 9px;',
  525. 'font-weight: bold;',
  526. 'color: #fff;',
  527. 'background: #666;',
  528. 'content: attr(badge);',
  529. '}'
  530. ].join(''));
  531. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  532. }
  533. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  534. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  535. };
  536. /******************************************************************************/
  537. vAPI.toolbarButton.remove = function(doc) {
  538. var panel = doc.getElementById(this.panelId);
  539. panel.parentNode.removeChild(panel);
  540. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  541. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  542. };
  543. /******************************************************************************/
  544. vAPI.messaging = {
  545. get globalMessageManager() {
  546. return Cc['@mozilla.org/globalmessagemanager;1']
  547. .getService(Ci.nsIMessageListenerManager);
  548. },
  549. frameScript: vAPI.getURL('frameScript.js'),
  550. listeners: {},
  551. defaultHandler: null,
  552. NOOPFUNC: function(){},
  553. UNHANDLED: 'vAPI.messaging.notHandled'
  554. };
  555. /******************************************************************************/
  556. vAPI.messaging.listen = function(listenerName, callback) {
  557. this.listeners[listenerName] = callback;
  558. };
  559. /******************************************************************************/
  560. vAPI.messaging.onMessage = function(request) {
  561. var messageManager = request.target.messageManager;
  562. if (!messageManager) {
  563. // Message came from a popup, and its message manager is not usable.
  564. // So instead we broadcast to the parent window.
  565. messageManager = request.target
  566. .webNavigation.QueryInterface(Ci.nsIDocShell)
  567. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  568. }
  569. var listenerId = request.data.portName.split('|');
  570. var requestId = request.data.requestId;
  571. var portName = listenerId[1];
  572. listenerId = listenerId[0];
  573. var callback = vAPI.messaging.NOOPFUNC;
  574. if ( requestId !== undefined ) {
  575. callback = function(response) {
  576. var message = JSON.stringify({
  577. requestId: requestId,
  578. portName: portName,
  579. msg: response !== undefined ? response : null
  580. });
  581. if (messageManager.sendAsyncMessage) {
  582. messageManager.sendAsyncMessage(listenerId, message);
  583. }
  584. else {
  585. messageManager.broadcastAsyncMessage(listenerId, message);
  586. }
  587. };
  588. }
  589. var sender = {
  590. tab: {
  591. id: vAPI.tabs.getTabId(request.target)
  592. }
  593. };
  594. // Specific handler
  595. var r = vAPI.messaging.UNHANDLED;
  596. var listener = vAPI.messaging.listeners[portName];
  597. if ( typeof listener === 'function' ) {
  598. r = listener(request.data.msg, sender, callback);
  599. }
  600. if ( r !== vAPI.messaging.UNHANDLED ) {
  601. return;
  602. }
  603. // Default handler
  604. r = vAPI.messaging.defaultHandler(request.data.msg, sender, callback);
  605. if ( r !== vAPI.messaging.UNHANDLED ) {
  606. return;
  607. }
  608. console.error('µBlock> messaging > unknown request: %o', request.data);
  609. // Unhandled:
  610. // Need to callback anyways in case caller expected an answer, or
  611. // else there is a memory leak on caller's side
  612. callback();
  613. };
  614. /******************************************************************************/
  615. vAPI.messaging.setup = function(defaultHandler) {
  616. // Already setup?
  617. if ( this.defaultHandler !== null ) {
  618. return;
  619. }
  620. if ( typeof defaultHandler !== 'function' ) {
  621. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  622. }
  623. this.defaultHandler = defaultHandler;
  624. this.globalMessageManager.addMessageListener(
  625. vAPI.app.cleanName + ':background',
  626. this.onMessage
  627. );
  628. this.globalMessageManager.loadFrameScript(vAPI.messaging.frameScript, true);
  629. vAPI.unload.push(function() {
  630. var gmm = vAPI.messaging.globalMessageManager;
  631. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  632. gmm.removeMessageListener(
  633. vAPI.app.cleanName + ':background',
  634. vAPI.messaging.onMessage
  635. );
  636. });
  637. };
  638. /******************************************************************************/
  639. vAPI.messaging.broadcast = function(message) {
  640. this.globalMessageManager.broadcastAsyncMessage(
  641. vAPI.app.cleanName + ':broadcast',
  642. JSON.stringify({broadcast: true, msg: message})
  643. );
  644. };
  645. /******************************************************************************/
  646. vAPI.net = {
  647. beforeRequestMessageName: vAPI.app.cleanName + ':onBeforeRequest'
  648. };
  649. /******************************************************************************/
  650. vAPI.net.registerListeners = function() {
  651. var types = {
  652. 2: 'script',
  653. 3: 'image',
  654. 4: 'stylesheet',
  655. 5: 'object',
  656. 6: 'main_frame',
  657. 7: 'sub_frame',
  658. 11: 'xmlhttprequest'
  659. };
  660. var onBeforeRequest = this.onBeforeRequest;
  661. this.onBeforeRequest = function(e) {
  662. var details = e.data;
  663. details.type = types[details.type] || 'other';
  664. details.tabId = vAPI.tabs.getTabId(e.target);
  665. if (onBeforeRequest.types.indexOf(details.type) === -1) {
  666. return false;
  667. }
  668. var block = onBeforeRequest.callback(details);
  669. if (block && typeof block === 'object') {
  670. if (block.cancel === true) {
  671. return true;
  672. }
  673. else if (block.redirectURL) {
  674. return block.redirectURL;
  675. }
  676. }
  677. return false;
  678. };
  679. vAPI.messaging.globalMessageManager.addMessageListener(
  680. this.beforeRequestMessageName,
  681. this.onBeforeRequest
  682. );
  683. vAPI.unload.push(function() {
  684. vAPI.messaging.globalMessageManager.removeMessageListener(
  685. vAPI.net.beforeRequestMessageName,
  686. vAPI.net.onBeforeRequest
  687. );
  688. });
  689. };
  690. /******************************************************************************/
  691. vAPI.contextMenu = {};
  692. /******************************************************************************/
  693. vAPI.contextMenu.create = function(details, callback) {};
  694. /******************************************************************************/
  695. vAPI.contextMenu.remove = function() {};
  696. /******************************************************************************/
  697. vAPI.lastError = function() {
  698. return null;
  699. };
  700. /******************************************************************************/
  701. // clean up when the extension is disabled
  702. window.addEventListener('unload', function() {
  703. for (var unload of vAPI.unload) {
  704. unload();
  705. }
  706. // frameModule needs to be cleared too
  707. var frameModule = {};
  708. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  709. frameModule.contentPolicy.unregister();
  710. frameModule.docObserver.unregister();
  711. Cu.unload(vAPI.getURL('frameModule.js'));
  712. });
  713. /******************************************************************************/
  714. })();
  715. /******************************************************************************/