content-fetch.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, window, document, CustomEvent */
  24. const FETCH_SUPPORTED_REQUEST_EVENT = "single-file-request-fetch-supported";
  25. const FETCH_SUPPORTED_RESPONSE_EVENT = "single-file-response-fetch-supported";
  26. const FETCH_REQUEST_EVENT = "single-file-request-fetch";
  27. const FETCH_RESPONSE_EVENT = "single-file-response-fetch";
  28. const ERR_HOST_FETCH = "Host fetch error (SingleFile)";
  29. const USE_HOST_FETCH = Boolean(window.wrappedJSObject);
  30. const fetch = (url, options) => window.fetch(url, options);
  31. let requestId = 0, pendingResponses = new Map(), hostFetchSupported;
  32. browser.runtime.onMessage.addListener(message => {
  33. if (message.method == "singlefile.fetchFrame" && window.frameId && window.frameId == message.frameId) {
  34. return onFetchFrame(message);
  35. }
  36. if (message.method == "singlefile.fetchResponse") {
  37. return onFetchResponse(message);
  38. }
  39. });
  40. async function onFetchFrame(message) {
  41. try {
  42. const response = await fetch(message.url, { cache: "force-cache", headers: message.headers });
  43. return {
  44. status: response.status,
  45. headers: [...response.headers],
  46. array: Array.from(new Uint8Array(await response.arrayBuffer()))
  47. };
  48. } catch (error) {
  49. return {
  50. error: error && error.toString()
  51. };
  52. }
  53. }
  54. async function onFetchResponse(message) {
  55. const pendingResponse = pendingResponses.get(message.requestId);
  56. if (pendingResponse) {
  57. if (message.error) {
  58. pendingResponse.reject(new Error(message.error));
  59. pendingResponses.delete(message.requestId);
  60. } else {
  61. if (message.truncated) {
  62. if (pendingResponse.array) {
  63. pendingResponse.array = pendingResponse.array.concat(message.array);
  64. } else {
  65. pendingResponse.array = message.array;
  66. pendingResponses.set(message.requestId, pendingResponse);
  67. }
  68. if (message.finished) {
  69. message.array = pendingResponse.array;
  70. }
  71. }
  72. if (!message.truncated || message.finished) {
  73. pendingResponse.resolve({
  74. status: message.status,
  75. headers: { get: headerName => message.headers && message.headers[headerName] },
  76. arrayBuffer: async () => new Uint8Array(message.array).buffer
  77. });
  78. pendingResponses.delete(message.requestId);
  79. }
  80. }
  81. }
  82. return {};
  83. }
  84. async function hostFetch(url, options) {
  85. if (hostFetchSupported === undefined) {
  86. hostFetchSupported = false;
  87. document.addEventListener(FETCH_SUPPORTED_RESPONSE_EVENT, () => hostFetchSupported = true, false);
  88. document.dispatchEvent(new CustomEvent(FETCH_SUPPORTED_REQUEST_EVENT));
  89. }
  90. if (hostFetchSupported) {
  91. const result = new Promise((resolve, reject) => {
  92. document.dispatchEvent(new CustomEvent(FETCH_REQUEST_EVENT, { detail: JSON.stringify({ url, options }) }));
  93. document.addEventListener(FETCH_RESPONSE_EVENT, onResponseFetch, false);
  94. function onResponseFetch(event) {
  95. if (event.detail) {
  96. if (event.detail.url == url) {
  97. document.removeEventListener(FETCH_RESPONSE_EVENT, onResponseFetch, false);
  98. if (event.detail.response) {
  99. resolve({
  100. status: event.detail.status,
  101. headers: new Map(event.detail.headers),
  102. arrayBuffer: async () => event.detail.response
  103. });
  104. } else {
  105. reject(event.detail.error);
  106. }
  107. }
  108. } else {
  109. reject();
  110. }
  111. }
  112. });
  113. try {
  114. return await result;
  115. } catch (error) {
  116. if (error && error.message == ERR_HOST_FETCH) {
  117. return fetch(url, options);
  118. } else {
  119. throw error;
  120. }
  121. }
  122. } else {
  123. return fetch(url, options);
  124. }
  125. }
  126. export {
  127. fetchResource as fetch,
  128. frameFetch
  129. };
  130. async function fetchResource(url, options = {}) {
  131. try {
  132. const fetchOptions = { cache: "force-cache", headers: options.headers, referrerPolicy: "strict-origin-when-cross-origin" };
  133. let response;
  134. try {
  135. if (options.referrer && !USE_HOST_FETCH) {
  136. response = await fetch(url, fetchOptions);
  137. } else {
  138. response = await hostFetch(url, fetchOptions);
  139. }
  140. } catch (error) {
  141. if (error && error.message == ERR_HOST_FETCH) {
  142. response = await fetch(url, fetchOptions);
  143. } else {
  144. throw error;
  145. }
  146. }
  147. return response;
  148. }
  149. catch (error) {
  150. requestId++;
  151. const promise = new Promise((resolve, reject) => pendingResponses.set(requestId, { resolve, reject }));
  152. await sendMessage({ method: "singlefile.fetch", url, requestId, referrer: options.referrer, headers: options.headers });
  153. return promise;
  154. }
  155. }
  156. async function frameFetch(url, options) {
  157. const response = await sendMessage({ method: "singlefile.fetchFrame", url, frameId: options.frameId, referrer: options.referrer, headers: options.headers });
  158. return {
  159. status: response.status,
  160. headers: new Map(response.headers),
  161. arrayBuffer: async () => new Uint8Array(response.array).buffer
  162. };
  163. }
  164. async function sendMessage(message) {
  165. const response = await browser.runtime.sendMessage(message);
  166. if (!response || response.error) {
  167. throw new Error(response && response.error && response.error.toString());
  168. } else {
  169. return response;
  170. }
  171. }