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.

947 lines
27 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 wintype = this.document.documentElement.getAttribute('windowtype');
  205. if (wintype !== '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('DOMContentLoaded', 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. // for internal use
  309. if (tab && callback === undefined) {
  310. return tab;
  311. }
  312. if (!tab) {
  313. callback();
  314. return;
  315. }
  316. var browser = tab.linkedBrowser;
  317. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  318. if (!windows) {
  319. windows = this.getWindows();
  320. }
  321. callback({
  322. id: tabId,
  323. index: gBrowser.browsers.indexOf(browser),
  324. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  325. active: tab === gBrowser.selectedTab,
  326. url: browser.currentURI.spec,
  327. title: tab.label
  328. });
  329. };
  330. /******************************************************************************/
  331. vAPI.tabs.getAll = function(window) {
  332. var tabs = [];
  333. for (var win of this.getWindows()) {
  334. if (window && window !== win) {
  335. continue;
  336. }
  337. for (var tab of win.gBrowser.tabs) {
  338. tabs.push(tab);
  339. }
  340. }
  341. return tabs;
  342. };
  343. /******************************************************************************/
  344. vAPI.tabs.getWindows = function() {
  345. var winumerator = Services.wm.getEnumerator('navigator:browser');
  346. var windows = [];
  347. while (winumerator.hasMoreElements()) {
  348. var win = winumerator.getNext();
  349. if (!win.closed) {
  350. windows.push(win);
  351. }
  352. }
  353. return windows;
  354. };
  355. /******************************************************************************/
  356. // properties of the details object:
  357. // url: 'URL', // the address that will be opened
  358. // tabId: 1, // the tab is used if set, instead of creating a new one
  359. // index: -1, // undefined: end of the list, -1: following tab, or after index
  360. // active: false, // opens the tab in background - true and undefined: foreground
  361. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  362. vAPI.tabs.open = function(details) {
  363. if (!details.url) {
  364. return null;
  365. }
  366. // extension pages
  367. if (!/^[\w-]{2,}:/.test(details.url)) {
  368. details.url = vAPI.getURL(details.url);
  369. }
  370. var tab, tabs;
  371. if (details.select) {
  372. var rgxHash = /#.*/;
  373. // this is questionable
  374. var url = details.url.replace(rgxHash, '');
  375. tabs = this.getAll();
  376. for (tab of tabs) {
  377. var browser = tab.linkedBrowser;
  378. if (browser.currentURI.spec.replace(rgxHash, '') === url) {
  379. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  380. return;
  381. }
  382. }
  383. }
  384. if (details.active === undefined) {
  385. details.active = true;
  386. }
  387. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  388. if (details.index === -1) {
  389. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  390. }
  391. if (details.tabId) {
  392. tabs = tabs || this.getAll();
  393. for (tab of tabs) {
  394. if (vAPI.tabs.getTabId(tab) === details.tabId) {
  395. tab.linkedBrowser.loadURI(details.url);
  396. return;
  397. }
  398. }
  399. }
  400. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  401. if (details.index !== undefined) {
  402. gBrowser.moveTabTo(tab, details.index);
  403. }
  404. };
  405. /******************************************************************************/
  406. vAPI.tabs.close = function(tabIds) {
  407. if (!Array.isArray(tabIds)) {
  408. tabIds = [tabIds];
  409. }
  410. tabIds = tabIds.map(function(tabId) {
  411. return 'tab[linkedpanel="panel-' + tabId + '"]';
  412. }).join(',');
  413. for (var win of this.getWindows()) {
  414. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  415. if (!tabs) {
  416. continue;
  417. }
  418. for (var tab of tabs) {
  419. win.gBrowser.removeTab(tab);
  420. }
  421. }
  422. };
  423. /******************************************************************************/
  424. vAPI.tabs.injectScript = function(tabId, details, callback) {
  425. var tab = vAPI.tabs.get(tabId);
  426. if (!tab) {
  427. return;
  428. }
  429. tab.linkedBrowser.messageManager.sendAsyncMessage(
  430. vAPI.app.cleanName + ':broadcast',
  431. JSON.stringify({
  432. broadcast: true,
  433. portName: 'vAPI',
  434. msg: {
  435. cmd: 'injectScript',
  436. details: details
  437. }
  438. })
  439. );
  440. if (typeof callback === 'function') {
  441. setTimeout(callback, 13);
  442. }
  443. };
  444. /******************************************************************************/
  445. vAPI.tabIcons = { /*tabId: {badge: 0, img: dict}*/ };
  446. vAPI.setIcon = function(tabId, img, badge) {
  447. var curWin = badge === undefined ? img : Services.wm.getMostRecentWindow('navigator:browser');
  448. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  449. // from 'TabSelect' event
  450. if (tabId === undefined) {
  451. tabId = curTabId;
  452. }
  453. else if (badge !== undefined) {
  454. vAPI.tabIcons[tabId] = {
  455. badge: badge === '>1K' ? '1k+' : badge,
  456. img: img && img[19] && img[19].replace(/19(-off)?\.png$/, '16$1.svg')
  457. };
  458. }
  459. if (tabId !== curTabId) {
  460. return;
  461. }
  462. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  463. var icon = vAPI.tabIcons[tabId];
  464. button.setAttribute('badge', icon && icon.badge || '');
  465. icon = vAPI.getURL(icon && icon.img || 'img/browsericons/icon16-off.svg');
  466. button.style.listStyleImage = 'url(' + icon + ')';
  467. };
  468. /******************************************************************************/
  469. vAPI.toolbarButton = {
  470. widgetId: vAPI.app.cleanName + '-button',
  471. panelId: vAPI.app.cleanName + '-panel'
  472. };
  473. /******************************************************************************/
  474. vAPI.toolbarButton.init = function() {
  475. CustomizableUI.createWidget({
  476. id: this.widgetId,
  477. type: 'view',
  478. viewId: this.panelId,
  479. defaultArea: CustomizableUI.AREA_NAVBAR,
  480. label: vAPI.app.name,
  481. tooltiptext: vAPI.app.name,
  482. onViewShowing: function(e) {
  483. e.target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  484. },
  485. onViewHiding: function(e) {
  486. e.target.firstChild.setAttribute('src', 'about:blank');
  487. }
  488. });
  489. vAPI.unload.push(function() {
  490. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  491. });
  492. };
  493. /******************************************************************************/
  494. // it runs with windowWatcher when a window is opened
  495. // vAPI.tabs.registerListeners initializes it
  496. vAPI.toolbarButton.add = function(doc) {
  497. var panel = doc.createElement('panelview');
  498. panel.id = this.panelId;
  499. var iframe = panel.appendChild(doc.createElement('iframe'));
  500. iframe.setAttribute('type', 'content');
  501. panel.style.overflow = iframe.style.overflow = 'hidden';
  502. doc.getElementById('PanelUI-multiView')
  503. .appendChild(panel)
  504. .appendChild(iframe);
  505. var updateTimer = null;
  506. var delayedResize = function() {
  507. if (updateTimer) {
  508. return;
  509. }
  510. updateTimer = setTimeout(resizePopup, 20);
  511. };
  512. var resizePopup = function() {
  513. var panelStyle = panel.style;
  514. var body = iframe.contentDocument.body;
  515. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  516. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  517. updateTimer = null;
  518. };
  519. var onPopupReady = function() {
  520. if (!this.contentWindow
  521. || this.contentWindow.location.host !== vAPI.app.cleanName) {
  522. return;
  523. }
  524. var mutObs = this.contentWindow.MutationObserver;
  525. (new mutObs(delayedResize)).observe(this.contentDocument, {
  526. childList: true,
  527. attributes: true,
  528. characterData: true,
  529. subtree: true
  530. });
  531. delayedResize();
  532. };
  533. iframe.addEventListener('load', onPopupReady, true);
  534. if (!this.styleURI) {
  535. this.styleURI = 'data:text/css,' + encodeURIComponent([
  536. '#' + this.widgetId + ' {',
  537. 'list-style-image: url(',
  538. vAPI.getURL('img/browsericons/icon16-off.svg'),
  539. ');',
  540. '}',
  541. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  542. 'position: absolute;',
  543. 'margin-left: -16px;',
  544. 'margin-top: 3px;',
  545. 'padding: 1px 2px;',
  546. 'font-size: 9px;',
  547. 'font-weight: bold;',
  548. 'color: #fff;',
  549. 'background: #666;',
  550. 'content: attr(badge);',
  551. '}',
  552. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  553. 'width: 180px;',
  554. 'height: 310px;',
  555. 'transition: width .1s, height .1s;',
  556. '}'
  557. ].join(''));
  558. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  559. }
  560. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  561. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  562. };
  563. /******************************************************************************/
  564. vAPI.toolbarButton.remove = function(doc) {
  565. var panel = doc.getElementById(this.panelId);
  566. panel.parentNode.removeChild(panel);
  567. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  568. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  569. };
  570. /******************************************************************************/
  571. vAPI.messaging = {
  572. get globalMessageManager() {
  573. return Cc['@mozilla.org/globalmessagemanager;1']
  574. .getService(Ci.nsIMessageListenerManager);
  575. },
  576. frameScript: vAPI.getURL('frameScript.js'),
  577. listeners: {},
  578. defaultHandler: null,
  579. NOOPFUNC: function(){},
  580. UNHANDLED: 'vAPI.messaging.notHandled'
  581. };
  582. /******************************************************************************/
  583. vAPI.messaging.listen = function(listenerName, callback) {
  584. this.listeners[listenerName] = callback;
  585. };
  586. /******************************************************************************/
  587. vAPI.messaging.onMessage = function(request) {
  588. var messageManager = request.target.messageManager;
  589. if (!messageManager) {
  590. // Message came from a popup, and its message manager is not usable.
  591. // So instead we broadcast to the parent window.
  592. messageManager = request.target
  593. .webNavigation.QueryInterface(Ci.nsIDocShell)
  594. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  595. }
  596. var listenerId = request.data.portName.split('|');
  597. var requestId = request.data.requestId;
  598. var portName = listenerId[1];
  599. listenerId = listenerId[0];
  600. var callback = vAPI.messaging.NOOPFUNC;
  601. if ( requestId !== undefined ) {
  602. callback = function(response) {
  603. var message = JSON.stringify({
  604. requestId: requestId,
  605. portName: portName,
  606. msg: response !== undefined ? response : null
  607. });
  608. if (messageManager.sendAsyncMessage) {
  609. messageManager.sendAsyncMessage(listenerId, message);
  610. }
  611. else {
  612. messageManager.broadcastAsyncMessage(listenerId, message);
  613. }
  614. };
  615. }
  616. var sender = {
  617. tab: {
  618. id: vAPI.tabs.getTabId(request.target)
  619. }
  620. };
  621. // Specific handler
  622. var r = vAPI.messaging.UNHANDLED;
  623. var listener = vAPI.messaging.listeners[portName];
  624. if ( typeof listener === 'function' ) {
  625. r = listener(request.data.msg, sender, callback);
  626. }
  627. if ( r !== vAPI.messaging.UNHANDLED ) {
  628. return;
  629. }
  630. // Default handler
  631. r = vAPI.messaging.defaultHandler(request.data.msg, sender, callback);
  632. if ( r !== vAPI.messaging.UNHANDLED ) {
  633. return;
  634. }
  635. console.error('µBlock> messaging > unknown request: %o', request.data);
  636. // Unhandled:
  637. // Need to callback anyways in case caller expected an answer, or
  638. // else there is a memory leak on caller's side
  639. callback();
  640. };
  641. /******************************************************************************/
  642. vAPI.messaging.setup = function(defaultHandler) {
  643. // Already setup?
  644. if ( this.defaultHandler !== null ) {
  645. return;
  646. }
  647. if ( typeof defaultHandler !== 'function' ) {
  648. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  649. }
  650. this.defaultHandler = defaultHandler;
  651. this.globalMessageManager.addMessageListener(
  652. vAPI.app.cleanName + ':background',
  653. this.onMessage
  654. );
  655. this.globalMessageManager.loadFrameScript(vAPI.messaging.frameScript, true);
  656. vAPI.unload.push(function() {
  657. var gmm = vAPI.messaging.globalMessageManager;
  658. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  659. gmm.removeMessageListener(
  660. vAPI.app.cleanName + ':background',
  661. vAPI.messaging.onMessage
  662. );
  663. });
  664. };
  665. /******************************************************************************/
  666. vAPI.messaging.broadcast = function(message) {
  667. this.globalMessageManager.broadcastAsyncMessage(
  668. vAPI.app.cleanName + ':broadcast',
  669. JSON.stringify({broadcast: true, msg: message})
  670. );
  671. };
  672. /******************************************************************************/
  673. vAPI.net = {
  674. beforeRequestMessageName: vAPI.app.cleanName + ':onBeforeRequest'
  675. };
  676. /******************************************************************************/
  677. vAPI.net.registerListeners = function() {
  678. var types = {
  679. 2: 'script',
  680. 3: 'image',
  681. 4: 'stylesheet',
  682. 5: 'object',
  683. 6: 'main_frame',
  684. 7: 'sub_frame',
  685. 11: 'xmlhttprequest'
  686. };
  687. var onBeforeRequest = this.onBeforeRequest;
  688. this.onBeforeRequest = function(e) {
  689. var details = e.data;
  690. details.type = types[details.type] || 'other';
  691. details.tabId = vAPI.tabs.getTabId(e.target);
  692. if (onBeforeRequest.types.indexOf(details.type) === -1) {
  693. return false;
  694. }
  695. var block = onBeforeRequest.callback(details);
  696. if (block && typeof block === 'object') {
  697. if (block.cancel === true) {
  698. return true;
  699. }
  700. else if (block.redirectURL) {
  701. return block.redirectURL;
  702. }
  703. }
  704. return false;
  705. };
  706. vAPI.messaging.globalMessageManager.addMessageListener(
  707. this.beforeRequestMessageName,
  708. this.onBeforeRequest
  709. );
  710. vAPI.unload.push(function() {
  711. vAPI.messaging.globalMessageManager.removeMessageListener(
  712. vAPI.net.beforeRequestMessageName,
  713. vAPI.net.onBeforeRequest
  714. );
  715. });
  716. };
  717. /******************************************************************************/
  718. vAPI.contextMenu = {};
  719. /******************************************************************************/
  720. vAPI.contextMenu.create = function(details, callback) {};
  721. /******************************************************************************/
  722. vAPI.contextMenu.remove = function() {};
  723. /******************************************************************************/
  724. vAPI.lastError = function() {
  725. return null;
  726. };
  727. /******************************************************************************/
  728. // clean up when the extension is disabled
  729. window.addEventListener('unload', function() {
  730. for (var unload of vAPI.unload) {
  731. unload();
  732. }
  733. // frameModule needs to be cleared too
  734. var frameModule = {};
  735. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  736. frameModule.contentPolicy.unregister();
  737. frameModule.docObserver.unregister();
  738. Cu.unload(vAPI.getURL('frameModule.js'));
  739. });
  740. /******************************************************************************/
  741. })();
  742. /******************************************************************************/