frame-tree.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global browser, window, top, document, HTMLHtmlElement, addEventListener, docHelper */
  21. this.FrameTree = this.FrameTree || (() => {
  22. const MESSAGE_PREFIX = "__FrameTree__";
  23. const TIMEOUT_INIT_REQUEST_MESSAGE = 500;
  24. const TIMEOUT_DATA_RESPONSE_MESSAGE = 500;
  25. const TIMEOUT_STEP = 100;
  26. const FrameTree = { getFramesData };
  27. const timeoutIds = [];
  28. const timeout = {
  29. set(fn, delay) {
  30. const id = timeoutIds.length;
  31. let elapsedTime = 0;
  32. timeoutIds[id] = setTimeout(step, 0);
  33. return id;
  34. function step() {
  35. if (elapsedTime < delay) {
  36. timeoutIds[id] = setTimeout(() => {
  37. elapsedTime += TIMEOUT_STEP;
  38. step();
  39. }, TIMEOUT_STEP);
  40. }
  41. else {
  42. fn();
  43. }
  44. }
  45. },
  46. clear(id) {
  47. if (timeoutIds[id]) {
  48. clearTimeout(timeoutIds[id]);
  49. timeoutIds[id] = null;
  50. }
  51. }
  52. };
  53. let framesData, dataRequestCallbacks;
  54. if (window == top) {
  55. browser.runtime.onMessage.addListener(message => {
  56. if (message.method == "FrameTree.initRequest" && document.documentElement instanceof HTMLHtmlElement) {
  57. dataRequestCallbacks = new Map();
  58. framesData = [];
  59. initRequest(message);
  60. }
  61. if (message.method == "FrameTree.getDataResponse") {
  62. getDataResponse(message);
  63. }
  64. });
  65. }
  66. browser.runtime.onMessage.addListener(message => {
  67. if (message.method == "FrameTree.getDataRequest" && FrameTree.windowId == message.windowId) {
  68. const docData = docHelper.preProcessDoc(document, window, message.options);
  69. browser.runtime.sendMessage({
  70. method: "FrameTree.getDataResponse",
  71. windowId: message.windowId,
  72. tabId: message.tabId,
  73. content: docHelper.serialize(document),
  74. emptyStyleRulesText: docData.emptyStyleRulesText,
  75. canvasData: docData.canvasData,
  76. baseURI: document.baseURI,
  77. title: document.title
  78. }).catch(() => {/* ignored */ });
  79. docHelper.postProcessDoc(document, message.options);
  80. }
  81. });
  82. addEventListener("message", event => {
  83. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX + "::")) {
  84. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length + 2));
  85. if (message.method == "initRequest") {
  86. initRequest(message);
  87. } else if (message.method == "initResponse") {
  88. initResponse(message);
  89. } else if (message.method == "getDataResponse") {
  90. getDataResponse(message);
  91. }
  92. }
  93. }, false);
  94. return FrameTree;
  95. async function getFramesData(options) {
  96. await Promise.all(framesData.map(async frameData => {
  97. return new Promise(resolve => {
  98. dataRequestCallbacks.set(frameData.windowId, resolve);
  99. if (frameData.sameDomain) {
  100. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataRequest", windowId: frameData.windowId, options: { removeHiddenElements: options.removeHiddenElements, compressHTML: options.compressHTML } }), "*");
  101. } else {
  102. browser.runtime.sendMessage({
  103. method: "FrameTree.getDataRequest",
  104. windowId: frameData.windowId,
  105. options: { removeHiddenElements: options.removeHiddenElements, compressHTML: options.compressHTML }
  106. }).catch(() => { /* ignored */ });
  107. }
  108. frameData.getDataResponseTimeout = timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: frameData.windowId }), "*"), TIMEOUT_DATA_RESPONSE_MESSAGE);
  109. });
  110. }));
  111. return framesData.sort((frame1, frame2) => frame2.windowId.split(".").length - frame1.windowId.split(".").length);
  112. }
  113. function initRequest(message) {
  114. FrameTree.windowId = message.windowId;
  115. FrameTree.index = message.index;
  116. const frameElements = document.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  117. if (frameElements.length) {
  118. setFramesWinId(MESSAGE_PREFIX, frameElements, message.options, FrameTree.index, FrameTree.windowId, window);
  119. } else {
  120. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: FrameTree.windowId, index: FrameTree.index }), "*");
  121. }
  122. }
  123. function initResponse(message) {
  124. if (window == top) {
  125. if (message.framesData) {
  126. message.framesData = message.framesData instanceof Array ? message.framesData : JSON.parse(message.framesData);
  127. framesData = framesData.concat(message.framesData);
  128. const frameData = framesData.find(frameData => frameData.windowId == message.windowId);
  129. const pendingCount = framesData.filter(frameData => !frameData.processed).length;
  130. if (message.windowId != "0") {
  131. frameData.processed = true;
  132. }
  133. if (!pendingCount || pendingCount == 1) {
  134. browser.runtime.sendMessage({ method: "FrameTree.initResponse" })
  135. .catch(() => { /* ignored */ });
  136. }
  137. }
  138. } else {
  139. FrameTree.windowId = message.windowId;
  140. FrameTree.index = message.index;
  141. }
  142. }
  143. function setFramesWinId(MESSAGE_PREFIX, frameElements, options, index, windowId, win) {
  144. const framesData = [];
  145. if (win != top) {
  146. win.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", windowId, index }), "*");
  147. }
  148. frameElements.forEach((frameElement, index) => {
  149. let src, sameDomain;
  150. try {
  151. sameDomain = Boolean(frameElement.contentDocument && frameElement.contentWindow && top.addEventListener && top);
  152. src = frameElement.src;
  153. } catch (error) {
  154. /* ignored */
  155. }
  156. framesData.push({ sameDomain, src, index, windowId: windowId + "." + index });
  157. });
  158. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData, windowId, index }), "*");
  159. frameElements.forEach((frameElement, index) => {
  160. const frameWinId = windowId + "." + index;
  161. frameElement.setAttribute(docHelper.WIN_ID_ATTRIBUTE_NAME, frameWinId);
  162. let frameDoc, frameWindow, topWindow;
  163. let content, emptyStyleRulesText, canvasData;
  164. try {
  165. frameDoc = frameElement.contentDocument;
  166. frameWindow = frameElement.contentWindow;
  167. topWindow = top.addEventListener && top;
  168. } catch (error) {
  169. /* ignored */
  170. }
  171. if (frameWindow && frameDoc && topWindow) {
  172. setFramesWinId(MESSAGE_PREFIX, frameDoc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"), options, index, frameWinId, frameWindow);
  173. topWindow.addEventListener("message", onMessage, false);
  174. const docData = docHelper.preProcessDoc(frameDoc, frameWindow, options);
  175. content = docHelper.serialize(frameDoc);
  176. emptyStyleRulesText = docData.emptyStyleRulesText;
  177. canvasData = docData.canvasData;
  178. docHelper.postProcessDoc(frameDoc, options);
  179. } else if (frameWindow) {
  180. frameWindow.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initRequest", windowId: frameWinId, index, options }), "*");
  181. timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: frameWinId, index }), "*"), TIMEOUT_INIT_REQUEST_MESSAGE);
  182. }
  183. function onMessage(event) {
  184. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX + "::")) {
  185. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length + 2));
  186. if (message.method == "getDataRequest" && message.windowId == frameWinId) {
  187. topWindow.removeEventListener("message", onMessage, false);
  188. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: message.windowId, content, baseURI: frameDoc.baseURI, title: document.title, emptyStyleRulesText, canvasData }), "*");
  189. }
  190. }
  191. }
  192. });
  193. }
  194. function getDataResponse(message) {
  195. delete message.tabId;
  196. delete message.method;
  197. const frameData = framesData.find(frameData => frameData.windowId == message.windowId);
  198. timeout.clear(frameData.getDataResponseTimeout);
  199. frameData.content = message.content;
  200. frameData.baseURI = message.baseURI;
  201. frameData.title = message.title;
  202. frameData.emptyStyleRulesText = message.emptyStyleRulesText;
  203. frameData.canvasData = message.canvasData;
  204. dataRequestCallbacks.get(message.windowId)(message);
  205. }
  206. })();