frame-tree.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 */
  21. this.FrameTree = this.FrameTree || (() => {
  22. const MESSAGE_PREFIX = "__FrameTree__";
  23. const TIMEOUT_INIT_REQUEST_MESSAGE = 1000;
  24. const TIMEOUT_DATA_RESPONSE_MESSAGE = 1000;
  25. const FrameTree = { getFramesData };
  26. let framesData, dataRequestCallbacks;
  27. if (window == top) {
  28. browser.runtime.onMessage.addListener(message => {
  29. if (message.method == "FrameTree.initRequest" && document.documentElement instanceof HTMLHtmlElement) {
  30. dataRequestCallbacks = new Map();
  31. framesData = [];
  32. initRequest(message);
  33. }
  34. if (message.method == "FrameTree.getDataResponse") {
  35. getDataResponse(message);
  36. }
  37. });
  38. }
  39. browser.runtime.onMessage.addListener(message => {
  40. if (message.method == "FrameTree.getDataRequest" && FrameTree.windowId == message.windowId) {
  41. browser.runtime.sendMessage({
  42. method: "FrameTree.getDataResponse",
  43. windowId: message.windowId,
  44. tabId: message.tabId,
  45. content: getDoctype(document) + document.documentElement.outerHTML,
  46. emptyStyleRulesText: getEmptyStyleRulesText(document),
  47. canvasData: getCanvasData(document),
  48. baseURI: document.baseURI,
  49. title: document.title
  50. }).catch(() => {/* ignored */ });
  51. }
  52. });
  53. addEventListener("message", event => {
  54. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX + "::")) {
  55. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length + 2));
  56. if (message.method == "initRequest") {
  57. initRequest(message);
  58. } else if (message.method == "initResponse") {
  59. initResponse(message);
  60. } else if (message.method == "getDataResponse") {
  61. getDataResponse(message);
  62. }
  63. }
  64. }, false);
  65. return FrameTree;
  66. async function getFramesData() {
  67. await Promise.all(framesData.map(async frameData => {
  68. return new Promise(resolve => {
  69. dataRequestCallbacks.set(frameData.windowId, resolve);
  70. if (frameData.sameDomain) {
  71. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataRequest", windowId: frameData.windowId }), "*");
  72. } else {
  73. browser.runtime.sendMessage({
  74. method: "FrameTree.getDataRequest",
  75. windowId: frameData.windowId
  76. }).catch(() => { /* ignored */ });
  77. }
  78. frameData.getDataResponseTimeout = setTimeout(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: frameData.windowId }), "*"), TIMEOUT_DATA_RESPONSE_MESSAGE);
  79. });
  80. }));
  81. return framesData.sort((frame1, frame2) => frame2.windowId.split(".").length - frame1.windowId.split(".").length);
  82. }
  83. function initRequest(message) {
  84. FrameTree.windowId = message.windowId;
  85. FrameTree.index = message.index;
  86. const frameElements = document.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  87. if (frameElements.length) {
  88. setFramesWinId(MESSAGE_PREFIX, frameElements, FrameTree.index, FrameTree.windowId, window);
  89. } else {
  90. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: FrameTree.windowId, index: FrameTree.index }), "*");
  91. }
  92. }
  93. function initResponse(message) {
  94. if (window == top) {
  95. if (message.framesData) {
  96. message.framesData = message.framesData instanceof Array ? message.framesData : JSON.parse(message.framesData);
  97. framesData = framesData.concat(message.framesData);
  98. const frameData = framesData.find(frameData => frameData.windowId == message.windowId);
  99. const pendingCount = framesData.filter(frameData => !frameData.processed).length;
  100. if (message.windowId != "0") {
  101. frameData.processed = true;
  102. }
  103. if (!pendingCount || pendingCount == 1) {
  104. browser.runtime.sendMessage({ method: "FrameTree.initResponse" })
  105. .catch(() => { /* ignored */ });
  106. }
  107. }
  108. } else {
  109. FrameTree.windowId = message.windowId;
  110. FrameTree.index = message.index;
  111. }
  112. }
  113. function setFramesWinId(MESSAGE_PREFIX, frameElements, index, windowId, win) {
  114. const framesData = [];
  115. if (win != top) {
  116. win.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", windowId, index }), "*");
  117. }
  118. frameElements.forEach((frameElement, index) => {
  119. let src, sameDomain;
  120. try {
  121. sameDomain = Boolean(frameElement.contentDocument && frameElement.contentWindow && top.addEventListener && top);
  122. src = frameElement.src;
  123. } catch (error) {
  124. /* ignored */
  125. }
  126. framesData.push({ sameDomain, src, index, windowId: windowId + "." + index });
  127. });
  128. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData, windowId, index }), "*");
  129. frameElements.forEach((frameElement, index) => {
  130. const frameWinId = windowId + "." + index;
  131. frameElement.setAttribute("data-frame-tree-win-id", frameWinId);
  132. let frameDoc, frameWindow, topWindow;
  133. try {
  134. frameDoc = frameElement.contentDocument;
  135. frameWindow = frameElement.contentWindow;
  136. topWindow = top.addEventListener && top;
  137. } catch (error) {
  138. /* ignored */
  139. }
  140. if (frameWindow && frameDoc && topWindow) {
  141. setFramesWinId(MESSAGE_PREFIX, frameDoc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"), index, frameWinId, frameWindow);
  142. topWindow.addEventListener("message", onMessage, false);
  143. } else if (frameWindow) {
  144. frameWindow.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initRequest", windowId: frameWinId, index }), "*");
  145. setTimeout(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: frameWinId, index }), "*"), TIMEOUT_INIT_REQUEST_MESSAGE);
  146. }
  147. function onMessage(event) {
  148. if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX + "::")) {
  149. const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length + 2));
  150. if (message.method == "getDataRequest" && message.windowId == frameWinId) {
  151. topWindow.removeEventListener("message", onMessage, false);
  152. const content = getDoctype(frameDoc) + frameDoc.documentElement.outerHTML;
  153. const emptyStyleRulesText = getEmptyStyleRulesText(frameDoc);
  154. const canvasData = getCanvasData(frameDoc);
  155. top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: message.windowId, content, baseURI: frameDoc.baseURI, title: document.title, emptyStyleRulesText, canvasData }), "*");
  156. }
  157. }
  158. }
  159. });
  160. }
  161. function getDataResponse(message) {
  162. delete message.tabId;
  163. delete message.method;
  164. const frameData = framesData.find(frameData => frameData.windowId == message.windowId);
  165. clearTimeout(frameData.getDataResponseTimeout);
  166. frameData.content = message.content;
  167. frameData.baseURI = message.baseURI;
  168. frameData.title = message.title;
  169. frameData.emptyStyleRulesText = message.emptyStyleRulesText;
  170. frameData.canvasData = message.canvasData;
  171. dataRequestCallbacks.get(message.windowId)(message);
  172. }
  173. function getDoctype(doc) {
  174. const docType = doc.doctype;
  175. let docTypeStr;
  176. if (docType) {
  177. docTypeStr = "<!DOCTYPE " + docType.nodeName;
  178. if (docType.publicId) {
  179. docTypeStr += " PUBLIC \"" + docType.publicId + "\"";
  180. if (docType.systemId) {
  181. docTypeStr += " \"" + docType.systemId + "\"";
  182. }
  183. } else if (docType.systemId) {
  184. docTypeStr += " SYSTEM \"" + docType.systemId + "\"";
  185. } if (docType.internalSubset) {
  186. docTypeStr += " [" + docType.internalSubset + "]";
  187. }
  188. return docTypeStr + ">\n";
  189. }
  190. return "";
  191. }
  192. function getEmptyStyleRulesText(doc) {
  193. if (doc) {
  194. const textData = [];
  195. doc.querySelectorAll("style").forEach(styleElement => {
  196. if (!styleElement.textContent) {
  197. textData.push(Array.from(styleElement.sheet.cssRules).map(rule => rule.cssText).join("\n"));
  198. }
  199. });
  200. return textData;
  201. }
  202. }
  203. function getCanvasData(doc) {
  204. if (doc) {
  205. const canvasData = [];
  206. doc.querySelectorAll("canvas").forEach(canvasElement => {
  207. try {
  208. canvasData.push({ dataURI: canvasElement.toDataURL("image/png", ""), width: canvasElement.clientWidth, height: canvasElement.clientHeight });
  209. } catch (error) {
  210. canvasData.push(null);
  211. }
  212. });
  213. return canvasData;
  214. }
  215. }
  216. })();