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.

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