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.

1083 lines
31 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.register(this.document);
  218. vAPI.contextMenu.register(this.document);
  219. // when new window is opened TabSelect doesn't run on the selected tab?
  220. },
  221. observe: function(win, topic) {
  222. if (topic === 'domwindowopened') {
  223. win.addEventListener('DOMContentLoaded', this.onReady);
  224. }
  225. }
  226. };
  227. /******************************************************************************/
  228. var tabsProgressListener = {
  229. onLocationChange: function(browser, webProgress, request, location, flags) {
  230. if (!webProgress.isTopLevel) {
  231. return;
  232. }
  233. var tabId = vAPI.tabs.getTabId(browser);
  234. if (flags & 1) {
  235. vAPI.tabs.onUpdated(tabId, {url: location.spec}, {
  236. frameId: 0,
  237. tabId: tabId,
  238. url: browser.currentURI.spec
  239. });
  240. }
  241. else {
  242. vAPI.tabs.onNavigation({
  243. frameId: 0,
  244. tabId: tabId,
  245. url: location.spec
  246. });
  247. }
  248. }
  249. };
  250. /******************************************************************************/
  251. vAPI.tabs = {};
  252. /******************************************************************************/
  253. vAPI.tabs.registerListeners = function() {
  254. // onNavigation and onUpdated handled with tabsProgressListener
  255. // onClosed - handled in windowWatcher.onTabClose
  256. // onPopup ?
  257. for (var win of this.getWindows()) {
  258. windowWatcher.onReady.call(win);
  259. }
  260. Services.ww.registerNotification(windowWatcher);
  261. vAPI.toolbarButton.init();
  262. vAPI.unload.push(function() {
  263. Services.ww.unregisterNotification(windowWatcher);
  264. for (var win of vAPI.tabs.getWindows()) {
  265. vAPI.toolbarButton.unregister(win.document);
  266. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  267. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  268. var tC = win.gBrowser.tabContainer;
  269. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  270. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  271. // close extension tabs
  272. for (var tab of win.gBrowser.tabs) {
  273. var URI = tab.linkedBrowser.currentURI;
  274. if (URI.scheme === 'chrome' && URI.host === location.host) {
  275. win.gBrowser.removeTab(tab);
  276. }
  277. }
  278. }
  279. });
  280. };
  281. /******************************************************************************/
  282. vAPI.tabs.getTabId = function(target) {
  283. if (target.linkedPanel) {
  284. return target.linkedPanel.slice(6);
  285. }
  286. var gBrowser = target.ownerDocument.defaultView.gBrowser;
  287. var i = gBrowser.browsers.indexOf(target);
  288. if (i !== -1) {
  289. i = gBrowser.tabs[i].linkedPanel.slice(6);
  290. }
  291. return i;
  292. };
  293. /******************************************************************************/
  294. vAPI.tabs.get = function(tabId, callback) {
  295. var tab, windows;
  296. if (tabId === null) {
  297. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  298. tabId = vAPI.tabs.getTabId(tab);
  299. }
  300. else {
  301. windows = this.getWindows();
  302. for (var win of windows) {
  303. tab = win.gBrowser.tabContainer.querySelector(
  304. 'tab[linkedpanel="panel-' + tabId + '"]'
  305. );
  306. if (tab) {
  307. break;
  308. }
  309. }
  310. }
  311. // for internal use
  312. if (tab && callback === undefined) {
  313. return tab;
  314. }
  315. if (!tab) {
  316. callback();
  317. return;
  318. }
  319. var browser = tab.linkedBrowser;
  320. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  321. if (!windows) {
  322. windows = this.getWindows();
  323. }
  324. callback({
  325. id: tabId,
  326. index: gBrowser.browsers.indexOf(browser),
  327. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  328. active: tab === gBrowser.selectedTab,
  329. url: browser.currentURI.spec,
  330. title: tab.label
  331. });
  332. };
  333. /******************************************************************************/
  334. vAPI.tabs.getAll = function(window) {
  335. var tabs = [];
  336. for (var win of this.getWindows()) {
  337. if (window && window !== win) {
  338. continue;
  339. }
  340. for (var tab of win.gBrowser.tabs) {
  341. tabs.push(tab);
  342. }
  343. }
  344. return tabs;
  345. };
  346. /******************************************************************************/
  347. vAPI.tabs.getWindows = function() {
  348. var winumerator = Services.wm.getEnumerator('navigator:browser');
  349. var windows = [];
  350. while (winumerator.hasMoreElements()) {
  351. var win = winumerator.getNext();
  352. if (!win.closed) {
  353. windows.push(win);
  354. }
  355. }
  356. return windows;
  357. };
  358. /******************************************************************************/
  359. // properties of the details object:
  360. // url: 'URL', // the address that will be opened
  361. // tabId: 1, // the tab is used if set, instead of creating a new one
  362. // index: -1, // undefined: end of the list, -1: following tab, or after index
  363. // active: false, // opens the tab in background - true and undefined: foreground
  364. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  365. vAPI.tabs.open = function(details) {
  366. if (!details.url) {
  367. return null;
  368. }
  369. // extension pages
  370. if (!/^[\w-]{2,}:/.test(details.url)) {
  371. details.url = vAPI.getURL(details.url);
  372. }
  373. var tab, tabs;
  374. if (details.select) {
  375. var rgxHash = /#.*/;
  376. // this is questionable
  377. var url = details.url.replace(rgxHash, '');
  378. tabs = this.getAll();
  379. for (tab of tabs) {
  380. var browser = tab.linkedBrowser;
  381. if (browser.currentURI.spec.replace(rgxHash, '') === url) {
  382. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  383. return;
  384. }
  385. }
  386. }
  387. if (details.active === undefined) {
  388. details.active = true;
  389. }
  390. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  391. if (details.index === -1) {
  392. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  393. }
  394. if (details.tabId) {
  395. tabs = tabs || this.getAll();
  396. for (tab of tabs) {
  397. if (vAPI.tabs.getTabId(tab) === details.tabId) {
  398. tab.linkedBrowser.loadURI(details.url);
  399. return;
  400. }
  401. }
  402. }
  403. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  404. if (details.index !== undefined) {
  405. gBrowser.moveTabTo(tab, details.index);
  406. }
  407. };
  408. /******************************************************************************/
  409. vAPI.tabs.close = function(tabIds) {
  410. if (!Array.isArray(tabIds)) {
  411. tabIds = [tabIds];
  412. }
  413. tabIds = tabIds.map(function(tabId) {
  414. return 'tab[linkedpanel="panel-' + tabId + '"]';
  415. }).join(',');
  416. for (var win of this.getWindows()) {
  417. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  418. if (!tabs) {
  419. continue;
  420. }
  421. for (var tab of tabs) {
  422. win.gBrowser.removeTab(tab);
  423. }
  424. }
  425. };
  426. /******************************************************************************/
  427. vAPI.tabs.injectScript = function(tabId, details, callback) {
  428. var tab = vAPI.tabs.get(tabId);
  429. if (!tab) {
  430. return;
  431. }
  432. tab.linkedBrowser.messageManager.sendAsyncMessage(
  433. location.host + ':broadcast',
  434. JSON.stringify({
  435. broadcast: true,
  436. portName: 'vAPI',
  437. msg: {
  438. cmd: 'injectScript',
  439. details: details
  440. }
  441. })
  442. );
  443. if (typeof callback === 'function') {
  444. setTimeout(callback, 13);
  445. }
  446. };
  447. /******************************************************************************/
  448. vAPI.tabIcons = { /*tabId: {badge: 0, img: dict}*/ };
  449. vAPI.setIcon = function(tabId, img, badge) {
  450. var curWin = badge === undefined ? img : Services.wm.getMostRecentWindow('navigator:browser');
  451. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  452. // from 'TabSelect' event
  453. if (tabId === undefined) {
  454. tabId = curTabId;
  455. }
  456. else if (badge !== undefined) {
  457. vAPI.tabIcons[tabId] = {
  458. badge: badge === '>1K' ? '1k+' : badge,
  459. img: img && img[19] && img[19].replace(/19(-off)?\.png$/, '16$1.svg')
  460. };
  461. }
  462. if (tabId !== curTabId) {
  463. return;
  464. }
  465. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  466. var icon = vAPI.tabIcons[tabId];
  467. button.setAttribute('badge', icon && icon.badge || '');
  468. icon = vAPI.getURL(icon && icon.img || 'img/browsericons/icon16-off.svg');
  469. button.style.listStyleImage = 'url(' + icon + ')';
  470. };
  471. /******************************************************************************/
  472. vAPI.toolbarButton = {
  473. widgetId: location.host + '-button',
  474. panelId: location.host + '-panel'
  475. };
  476. /******************************************************************************/
  477. vAPI.toolbarButton.init = function() {
  478. CustomizableUI.createWidget({
  479. id: this.widgetId,
  480. type: 'view',
  481. viewId: this.panelId,
  482. defaultArea: CustomizableUI.AREA_NAVBAR,
  483. label: vAPI.app.name,
  484. tooltiptext: vAPI.app.name,
  485. onViewShowing: function(e) {
  486. e.target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  487. },
  488. onViewHiding: function(e) {
  489. e.target.firstChild.setAttribute('src', 'about:blank');
  490. }
  491. });
  492. vAPI.unload.push(function() {
  493. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  494. });
  495. };
  496. /******************************************************************************/
  497. // it runs with windowWatcher when a window is opened
  498. // vAPI.tabs.registerListeners initializes it
  499. vAPI.toolbarButton.register = function(doc) {
  500. var panel = doc.createElement('panelview');
  501. panel.setAttribute('id', this.panelId);
  502. var iframe = panel.appendChild(doc.createElement('iframe'));
  503. iframe.setAttribute('type', 'content');
  504. panel.style.overflow = iframe.style.overflow = 'hidden';
  505. doc.getElementById('PanelUI-multiView')
  506. .appendChild(panel)
  507. .appendChild(iframe);
  508. var updateTimer = null;
  509. var delayedResize = function() {
  510. if (updateTimer) {
  511. return;
  512. }
  513. updateTimer = setTimeout(resizePopup, 20);
  514. };
  515. var resizePopup = function() {
  516. var panelStyle = panel.style;
  517. var body = iframe.contentDocument.body;
  518. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  519. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  520. updateTimer = null;
  521. };
  522. var onPopupReady = function() {
  523. if (!this.contentWindow
  524. || this.contentWindow.location.host !== location.host) {
  525. return;
  526. }
  527. var mutObs = this.contentWindow.MutationObserver;
  528. (new mutObs(delayedResize)).observe(this.contentDocument, {
  529. childList: true,
  530. attributes: true,
  531. characterData: true,
  532. subtree: true
  533. });
  534. delayedResize();
  535. };
  536. iframe.addEventListener('load', onPopupReady, true);
  537. if (!this.styleURI) {
  538. this.styleURI = 'data:text/css,' + encodeURIComponent([
  539. '#' + this.widgetId + ' {',
  540. 'list-style-image: url(',
  541. vAPI.getURL('img/browsericons/icon16-off.svg'),
  542. ');',
  543. '}',
  544. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  545. 'position: absolute;',
  546. 'margin-left: -16px;',
  547. 'margin-top: 3px;',
  548. 'padding: 1px 2px;',
  549. 'font-size: 9px;',
  550. 'font-weight: bold;',
  551. 'color: #fff;',
  552. 'background: #666;',
  553. 'content: attr(badge);',
  554. '}',
  555. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  556. 'width: 180px;',
  557. 'height: 310px;',
  558. 'transition: width .1s, height .1s;',
  559. '}'
  560. ].join(''));
  561. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  562. }
  563. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  564. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  565. };
  566. /******************************************************************************/
  567. vAPI.toolbarButton.unregister = function(doc) {
  568. var panel = doc.getElementById(this.panelId);
  569. panel.parentNode.removeChild(panel);
  570. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  571. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  572. };
  573. /******************************************************************************/
  574. vAPI.messaging = {
  575. get globalMessageManager() {
  576. return Cc['@mozilla.org/globalmessagemanager;1']
  577. .getService(Ci.nsIMessageListenerManager);
  578. },
  579. frameScript: vAPI.getURL('frameScript.js'),
  580. listeners: {},
  581. defaultHandler: null,
  582. NOOPFUNC: function(){},
  583. UNHANDLED: 'vAPI.messaging.notHandled'
  584. };
  585. /******************************************************************************/
  586. vAPI.messaging.listen = function(listenerName, callback) {
  587. this.listeners[listenerName] = callback;
  588. };
  589. /******************************************************************************/
  590. vAPI.messaging.onMessage = function(request) {
  591. var messageManager = request.target.messageManager;
  592. if (!messageManager) {
  593. // Message came from a popup, and its message manager is not usable.
  594. // So instead we broadcast to the parent window.
  595. messageManager = request.target
  596. .webNavigation.QueryInterface(Ci.nsIDocShell)
  597. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  598. }
  599. var listenerId = request.data.portName.split('|');
  600. var requestId = request.data.requestId;
  601. var portName = listenerId[1];
  602. listenerId = listenerId[0];
  603. var callback = vAPI.messaging.NOOPFUNC;
  604. if ( requestId !== undefined ) {
  605. callback = function(response) {
  606. var message = JSON.stringify({
  607. requestId: requestId,
  608. portName: portName,
  609. msg: response !== undefined ? response : null
  610. });
  611. if (messageManager.sendAsyncMessage) {
  612. messageManager.sendAsyncMessage(listenerId, message);
  613. }
  614. else {
  615. messageManager.broadcastAsyncMessage(listenerId, message);
  616. }
  617. };
  618. }
  619. var sender = {
  620. tab: {
  621. id: vAPI.tabs.getTabId(request.target)
  622. }
  623. };
  624. // Specific handler
  625. var r = vAPI.messaging.UNHANDLED;
  626. var listener = vAPI.messaging.listeners[portName];
  627. if ( typeof listener === 'function' ) {
  628. r = listener(request.data.msg, sender, callback);
  629. }
  630. if ( r !== vAPI.messaging.UNHANDLED ) {
  631. return;
  632. }
  633. // Default handler
  634. r = vAPI.messaging.defaultHandler(request.data.msg, sender, callback);
  635. if ( r !== vAPI.messaging.UNHANDLED ) {
  636. return;
  637. }
  638. console.error('µBlock> messaging > unknown request: %o', request.data);
  639. // Unhandled:
  640. // Need to callback anyways in case caller expected an answer, or
  641. // else there is a memory leak on caller's side
  642. callback();
  643. };
  644. /******************************************************************************/
  645. vAPI.messaging.setup = function(defaultHandler) {
  646. // Already setup?
  647. if ( this.defaultHandler !== null ) {
  648. return;
  649. }
  650. if ( typeof defaultHandler !== 'function' ) {
  651. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  652. }
  653. this.defaultHandler = defaultHandler;
  654. this.globalMessageManager.addMessageListener(
  655. location.host + ':background',
  656. this.onMessage
  657. );
  658. this.globalMessageManager.loadFrameScript(vAPI.messaging.frameScript, true);
  659. vAPI.unload.push(function() {
  660. var gmm = vAPI.messaging.globalMessageManager;
  661. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  662. gmm.removeMessageListener(
  663. location.host + ':background',
  664. vAPI.messaging.onMessage
  665. );
  666. });
  667. };
  668. /******************************************************************************/
  669. vAPI.messaging.broadcast = function(message) {
  670. this.globalMessageManager.broadcastAsyncMessage(
  671. location.host + ':broadcast',
  672. JSON.stringify({broadcast: true, msg: message})
  673. );
  674. };
  675. /******************************************************************************/
  676. vAPI.net = {
  677. beforeRequestMessageName: location.host + ':onBeforeRequest'
  678. };
  679. /******************************************************************************/
  680. vAPI.net.registerListeners = function() {
  681. var types = {
  682. 2: 'script',
  683. 3: 'image',
  684. 4: 'stylesheet',
  685. 5: 'object',
  686. 6: 'main_frame',
  687. 7: 'sub_frame',
  688. 11: 'xmlhttprequest'
  689. };
  690. var onBeforeRequest = this.onBeforeRequest;
  691. this.onBeforeRequest = function(e) {
  692. var details = e.data;
  693. details.type = types[details.type] || 'other';
  694. details.tabId = vAPI.tabs.getTabId(e.target);
  695. if (onBeforeRequest.types.indexOf(details.type) === -1) {
  696. return false;
  697. }
  698. var block = onBeforeRequest.callback(details);
  699. if (block && typeof block === 'object') {
  700. if (block.cancel === true) {
  701. return true;
  702. }
  703. else if (block.redirectURL) {
  704. return block.redirectURL;
  705. }
  706. }
  707. return false;
  708. };
  709. vAPI.messaging.globalMessageManager.addMessageListener(
  710. this.beforeRequestMessageName,
  711. this.onBeforeRequest
  712. );
  713. vAPI.unload.push(function() {
  714. vAPI.messaging.globalMessageManager.removeMessageListener(
  715. vAPI.net.beforeRequestMessageName,
  716. vAPI.net.onBeforeRequest
  717. );
  718. });
  719. };
  720. /******************************************************************************/
  721. vAPI.contextMenu = {
  722. contextMap: {
  723. frame: 'inFrame',
  724. link: 'onLink',
  725. image: 'onImage',
  726. audio: 'onAudio',
  727. video: 'onVideo',
  728. editable: 'onEditableArea'
  729. }
  730. };
  731. /******************************************************************************/
  732. vAPI.contextMenu.displayMenuItem = function(e) {
  733. var doc = e.target.ownerDocument;
  734. var gContextMenu = doc.defaultView.gContextMenu;
  735. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  736. if (!/^https?$/.test(gContextMenu.browser.currentURI.scheme)) {
  737. menuitem.hidden = true;
  738. return;
  739. }
  740. var ctx = vAPI.contextMenu.contexts;
  741. if (!ctx) {
  742. menuitem.hidden = false;
  743. return;
  744. }
  745. var ctxMap = vAPI.contextMenu.contextMap;
  746. for (var context of ctx) {
  747. if (context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  748. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  749. && !gContextMenu.onVideo && !gContextMenu.onAudio) {
  750. menuitem.hidden = false;
  751. return;
  752. }
  753. if (gContextMenu[ctxMap[context]]) {
  754. menuitem.hidden = false;
  755. return;
  756. }
  757. }
  758. menuitem.hidden = true;
  759. };
  760. /******************************************************************************/
  761. vAPI.contextMenu.register = function(doc) {
  762. if (!this.menuItemId) {
  763. return;
  764. }
  765. var contextMenu = doc.getElementById('contentAreaContextMenu');
  766. var menuitem = doc.createElement('menuitem');
  767. menuitem.setAttribute('id', this.menuItemId);
  768. menuitem.setAttribute('label', this.menuLabel);
  769. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  770. menuitem.setAttribute('class', 'menuitem-iconic');
  771. menuitem.addEventListener('command', this.onCommand);
  772. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  773. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  774. };
  775. /******************************************************************************/
  776. vAPI.contextMenu.unregister = function(doc) {
  777. if (!this.menuItemId) {
  778. return;
  779. }
  780. var menuitem = doc.getElementById(this.menuItemId);
  781. var contextMenu = menuitem.parentNode;
  782. menuitem.removeEventListener('command', this.onCommand);
  783. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  784. contextMenu.removeChild(menuitem);
  785. };
  786. /******************************************************************************/
  787. vAPI.contextMenu.create = function(details, callback) {
  788. this.menuItemId = details.id;
  789. this.menuLabel = details.title;
  790. this.contexts = details.contexts;
  791. if (Array.isArray(this.contexts) && this.contexts.length) {
  792. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  793. }
  794. else {
  795. // default in Chrome
  796. this.contexts = ['page'];
  797. }
  798. this.onCommand = function() {
  799. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  800. var details = {
  801. menuItemId: this.id,
  802. tagName: gContextMenu.target.tagName.toLowerCase()
  803. };
  804. if (gContextMenu.inFrame) {
  805. details.frameUrl = gContextMenu.focusedWindow.location.href;
  806. }
  807. else if (gContextMenu.onImage
  808. || gContextMenu.onAudio
  809. || gContextMenu.onVideo) {
  810. details.srcUrl = gContextMenu.mediaURL;
  811. }
  812. else if (gContextMenu.onLink) {
  813. details.linkUrl = gContextMenu.linkURL;
  814. }
  815. callback(details, {
  816. id: vAPI.tabs.getTabId(gContextMenu.browser),
  817. url: gContextMenu.browser.currentURI.spec
  818. });
  819. };
  820. for (var win of vAPI.tabs.getWindows()) {
  821. this.register(win.document);
  822. }
  823. };
  824. /******************************************************************************/
  825. vAPI.contextMenu.remove = function() {
  826. for (var win of vAPI.tabs.getWindows()) {
  827. this.unregister(win.document);
  828. }
  829. this.menuItemId = null;
  830. this.menuLabel = null;
  831. this.contexts = null;
  832. this.onCommand = null;
  833. };
  834. /******************************************************************************/
  835. vAPI.lastError = function() {
  836. return null;
  837. };
  838. /******************************************************************************/
  839. // clean up when the extension is disabled
  840. window.addEventListener('unload', function() {
  841. for (var unload of vAPI.unload) {
  842. unload();
  843. }
  844. // frameModule needs to be cleared too
  845. var frameModule = {};
  846. Cu['import'](vAPI.getURL('frameModule.js'), frameModule);
  847. frameModule.contentPolicy.unregister();
  848. frameModule.docObserver.unregister();
  849. Cu.unload(vAPI.getURL('frameModule.js'));
  850. });
  851. /******************************************************************************/
  852. })();
  853. /******************************************************************************/