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.

949 lines
27 KiB

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