msg.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /* global URLS deepCopy deepMerge getOwnTab */// toolbox.js - not used in content scripts
  2. 'use strict';
  3. (() => {
  4. if (window.INJECTED === 1) return;
  5. const TARGETS = Object.assign(Object.create(null), {
  6. all: ['both', 'tab', 'extension'],
  7. extension: ['both', 'extension'],
  8. tab: ['both', 'tab'],
  9. });
  10. const NEEDS_TAB_IN_SENDER = [
  11. 'getTabUrlPrefix',
  12. 'updateIconBadge',
  13. 'styleViaAPI',
  14. ];
  15. const ERR_NO_RECEIVER = 'Receiving end does not exist';
  16. const ERR_PORT_CLOSED = 'The message port closed before';
  17. const handler = {
  18. both: new Set(),
  19. tab: new Set(),
  20. extension: new Set(),
  21. };
  22. // TODO: maybe move into polyfill.js and hook addListener to wrap/unwrap automatically
  23. chrome.runtime.onMessage.addListener(onRuntimeMessage);
  24. const msg = window.msg = {
  25. isBg: getExtBg() === window,
  26. async broadcast(data) {
  27. const requests = [msg.send(data, 'both').catch(msg.ignoreError)];
  28. for (const tab of await browser.tabs.query({})) {
  29. const url = tab.pendingUrl || tab.url;
  30. if (!tab.discarded &&
  31. !url.startsWith(URLS.ownOrigin) &&
  32. URLS.supported(url)) {
  33. requests[tab.active ? 'unshift' : 'push'](
  34. msg.sendTab(tab.id, data, null, 'both').catch(msg.ignoreError));
  35. }
  36. }
  37. return Promise.all(requests);
  38. },
  39. broadcastExtension(...args) {
  40. return msg.send(...args).catch(msg.ignoreError);
  41. },
  42. isIgnorableError(err) {
  43. const text = `${err && err.message || err}`;
  44. return text.includes(ERR_NO_RECEIVER) || text.includes(ERR_PORT_CLOSED);
  45. },
  46. ignoreError(err) {
  47. if (!msg.isIgnorableError(err)) {
  48. console.warn(err);
  49. }
  50. },
  51. on(fn) {
  52. handler.both.add(fn);
  53. },
  54. onTab(fn) {
  55. handler.tab.add(fn);
  56. },
  57. onExtension(fn) {
  58. handler.extension.add(fn);
  59. },
  60. off(fn) {
  61. for (const type of TARGETS.all) {
  62. handler[type].delete(fn);
  63. }
  64. },
  65. send(data, target = 'extension') {
  66. return browser.runtime.sendMessage({data, target})
  67. .then(unwrapResponse);
  68. },
  69. sendTab(tabId, data, options, target = 'tab') {
  70. return browser.tabs.sendMessage(tabId, {data, target}, options)
  71. .then(unwrapResponse);
  72. },
  73. _execute(types, ...args) {
  74. let result;
  75. if (!(args[0] instanceof Object)) {
  76. /* Data from other windows must be deep-copied to allow for GC in Chrome and
  77. merely survive in FF as it kills cross-window objects when their tab is closed. */
  78. args = args.map(deepCopy);
  79. }
  80. for (const type of types) {
  81. for (const fn of handler[type]) {
  82. let res;
  83. try {
  84. res = fn(...args);
  85. } catch (err) {
  86. res = Promise.reject(err);
  87. }
  88. if (res !== undefined && result === undefined) {
  89. result = res;
  90. }
  91. }
  92. }
  93. return result;
  94. },
  95. };
  96. function getExtBg() {
  97. const fn = chrome.extension.getBackgroundPage;
  98. const bg = fn && fn();
  99. return bg === window || bg && bg.msg && bg.msg.isBgReady ? bg : null;
  100. }
  101. function onRuntimeMessage({data, target}, sender, sendResponse) {
  102. const res = msg._execute(TARGETS[target] || TARGETS.all, data, sender);
  103. if (res instanceof Promise) {
  104. res.then(wrapData, wrapError).then(sendResponse);
  105. return true;
  106. }
  107. if (res !== undefined) sendResponse(wrapData(res));
  108. }
  109. function wrapData(data) {
  110. return {data};
  111. }
  112. function wrapError(error) {
  113. return {
  114. error: Object.assign({
  115. message: error.message || `${error}`,
  116. stack: error.stack,
  117. }, error), // passing custom properties e.g. `error.index`
  118. };
  119. }
  120. function unwrapResponse({data, error} = {error: {message: ERR_NO_RECEIVER}}) {
  121. return error
  122. ? Promise.reject(Object.assign(new Error(error.message), error))
  123. : data;
  124. }
  125. const apiHandler = !msg.isBg && {
  126. get({path}, name) {
  127. const fn = () => {};
  128. fn.path = [...path, name];
  129. return new Proxy(fn, apiHandler);
  130. },
  131. async apply({path}, thisObj, args) {
  132. const bg = getExtBg() ||
  133. chrome.tabs && await browser.runtime.getBackgroundPage().catch(() => {});
  134. const message = {method: 'invokeAPI', path, args};
  135. let res;
  136. // content scripts, probably private tabs, and our extension tab during Chrome startup
  137. if (!bg) {
  138. res = msg.send(message);
  139. } else {
  140. res = deepMerge(await bg.msg._execute(TARGETS.extension, message, {
  141. frameId: 0, // false in case of our Options frame but we really want to fetch styles early
  142. tab: NEEDS_TAB_IN_SENDER.includes(path.join('.')) && await getOwnTab(),
  143. url: location.href,
  144. }));
  145. }
  146. return res;
  147. },
  148. };
  149. /** @type {API} */
  150. window.API = msg.isBg ? {} : new Proxy({path: []}, apiHandler);
  151. })();