content-hooks-frames.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /*
  2. * Copyright 2010-2019 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 window */
  24. this.singlefile.lib.hooks.content.frames = this.singlefile.lib.hooks.content.frames || (() => {
  25. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  26. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  27. const BLOCK_COOKIES_START_EVENT = "single-file-block-cookies-start";
  28. const BLOCK_COOKIES_END_EVENT = "single-file-block-cookies-end";
  29. const BLOCK_STORAGE_START_EVENT = "single-file-block-storage-start";
  30. const BLOCK_STORAGE_END_EVENT = "single-file-block-storage-end";
  31. const LOAD_IMAGE_EVENT = "single-file-load-image";
  32. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  33. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  34. const addEventListener = window.addEventListener;
  35. const dispatchEvent = window.dispatchEvent;
  36. const CustomEvent = window.CustomEvent;
  37. const document = window.document;
  38. const HTMLDocument = window.HTMLDocument;
  39. const fontFaces = [];
  40. if (document instanceof HTMLDocument) {
  41. const scriptElement = document.createElement("script");
  42. scriptElement.textContent = "(" + injectedScript.toString() + ")()";
  43. document.documentElement.prepend(scriptElement);
  44. scriptElement.remove();
  45. addEventListener.call(window, NEW_FONT_FACE_EVENT, event => fontFaces.push(event.detail));
  46. }
  47. return {
  48. getFontsData: () => fontFaces,
  49. loadDeferredImagesStart: options => {
  50. if (options.loadDeferredImagesBlockCookies) {
  51. dispatchEvent.call(window, new CustomEvent(BLOCK_COOKIES_START_EVENT));
  52. }
  53. if (options.loadDeferredImagesBlockStorage) {
  54. dispatchEvent.call(window, new CustomEvent(BLOCK_STORAGE_START_EVENT));
  55. }
  56. dispatchEvent.call(window, new CustomEvent(LOAD_DEFERRED_IMAGES_START_EVENT));
  57. },
  58. loadDeferredImagesEnd: options => {
  59. if (options.loadDeferredImagesBlockCookies) {
  60. dispatchEvent.call(window, new CustomEvent(BLOCK_COOKIES_END_EVENT));
  61. }
  62. if (options.loadDeferredImagesBlockStorage) {
  63. dispatchEvent.call(window, new CustomEvent(BLOCK_STORAGE_END_EVENT));
  64. }
  65. dispatchEvent.call(window, new CustomEvent(LOAD_DEFERRED_IMAGES_END_EVENT));
  66. },
  67. LOAD_IMAGE_EVENT,
  68. IMAGE_LOADED_EVENT
  69. };
  70. function injectedScript() {
  71. const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
  72. const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
  73. const BLOCK_COOKIES_START_EVENT = "single-file-block-cookies-start";
  74. const BLOCK_COOKIES_END_EVENT = "single-file-block-cookies-end";
  75. const BLOCK_STORAGE_START_EVENT = "single-file-block-storage-start";
  76. const BLOCK_STORAGE_END_EVENT = "single-file-block-storage-end";
  77. const LOAD_IMAGE_EVENT = "single-file-load-image";
  78. const IMAGE_LOADED_EVENT = "single-file-image-loaded";
  79. const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
  80. const FONT_STYLE_PROPERTIES = {
  81. family: "font-family",
  82. style: "font-style",
  83. weight: "font-weight",
  84. stretch: "font-stretch",
  85. unicodeRange: "unicode-range",
  86. variant: "font-variant",
  87. featureSettings: "font-feature-settings"
  88. };
  89. const addEventListener = window.addEventListener;
  90. const dispatchEvent = window.dispatchEvent;
  91. const CustomEvent = window.CustomEvent;
  92. const document = window.document;
  93. const screen = window.screen;
  94. const Element = window.Element;
  95. const UIEvent = window.UIEvent;
  96. const FileReader = window.FileReader;
  97. const Blob = window.Blob;
  98. const requestAnimationFrame = window.requestAnimationFrame;
  99. const cancelAnimationFrame = window.cancelAnimationFrame;
  100. const console = window.console;
  101. const warn = console.warn;
  102. const observers = new Map();
  103. const observedElements = new Map();
  104. let loadDeferredImages;
  105. addEventListener.call(window, LOAD_DEFERRED_IMAGES_START_EVENT, () => {
  106. loadDeferredImages = true;
  107. const scrollingElement = document.scrollingElement || document.documentElement;
  108. const clientHeight = scrollingElement.clientHeight;
  109. const clientWidth = scrollingElement.clientWidth;
  110. const scrollHeight = Math.max(scrollingElement.scrollHeight - (clientHeight * .5), clientHeight);
  111. const scrollWidth = Math.max(scrollingElement.scrollWidth - (clientWidth * .5), clientWidth);
  112. scrollingElement.__defineGetter__("clientHeight", () => scrollHeight);
  113. scrollingElement.__defineGetter__("clientWidth", () => scrollWidth);
  114. screen.__defineGetter__("height", () => scrollHeight);
  115. screen.__defineGetter__("width", () => scrollWidth);
  116. if (!window._singleFile_getBoundingClientRect) {
  117. window._singleFile_getBoundingClientRect = Element.prototype.getBoundingClientRect;
  118. Element.prototype.getBoundingClientRect = function () {
  119. const boundingRect = window._singleFile_getBoundingClientRect.call(this);
  120. if (this == scrollingElement) {
  121. boundingRect.__defineGetter__("height", () => scrollHeight);
  122. boundingRect.__defineGetter__("bottom", () => scrollHeight + boundingRect.top);
  123. boundingRect.__defineGetter__("width", () => scrollWidth);
  124. boundingRect.__defineGetter__("right", () => scrollWidth + boundingRect.left);
  125. }
  126. return boundingRect;
  127. };
  128. window._singleFile_innerHeight = window.innerHeight;
  129. window._singleFile_innerWidth = window.innerWidth;
  130. window.__defineGetter__("innerHeight", () => scrollHeight);
  131. window.__defineGetter__("innerWidth", () => scrollWidth);
  132. }
  133. if (!window._singleFileImage) {
  134. const Image = window.Image;
  135. window._singleFileImage = window.Image;
  136. window.__defineGetter__("Image", function () {
  137. return function () {
  138. const image = new Image(...arguments);
  139. const result = new Image(...arguments);
  140. result.__defineSetter__("src", function (value) {
  141. image.src = value;
  142. dispatchEvent.call(window, new CustomEvent(LOAD_IMAGE_EVENT, { detail: image.src }));
  143. });
  144. result.__defineGetter__("src", function () {
  145. return image.src;
  146. });
  147. result.__defineSetter__("srcset", function (value) {
  148. dispatchEvent.call(window, new CustomEvent(LOAD_IMAGE_EVENT));
  149. image.srcset = value;
  150. });
  151. result.__defineGetter__("srcset", function () {
  152. return image.srcset;
  153. });
  154. image.onload = image.onloadend = image.onerror = event => {
  155. dispatchEvent.call(window, new CustomEvent(IMAGE_LOADED_EVENT, { detail: image.src }));
  156. result.dispatchEvent(new UIEvent(event.type, event));
  157. };
  158. if (image.decode) {
  159. result.decode = () => image.decode();
  160. }
  161. return result;
  162. };
  163. });
  164. }
  165. const zoomFactorX = (clientHeight + window.scrollY) / scrollHeight;
  166. const zoomFactorY = (clientWidth + window.scrollX) / scrollWidth;
  167. const zoomFactor = Math.min(zoomFactorX, zoomFactorY);
  168. if (zoomFactor < 1) {
  169. const transform = document.documentElement.style.getPropertyValue("transform");
  170. const transformPriority = document.documentElement.style.getPropertyPriority("transform");
  171. const transformOrigin = document.documentElement.style.getPropertyValue("transform-origin");
  172. const transformOriginPriority = document.documentElement.style.getPropertyPriority("transform-origin");
  173. document.documentElement.style.setProperty("transform-origin", (zoomFactorX < 1 ? "50%" : "0") + " " + (zoomFactorY < 1 ? "50%" : "0") + " 0", "important");
  174. document.documentElement.style.setProperty("transform", "scale3d(" + zoomFactor + ", " + zoomFactor + ", 1)", "important");
  175. dispatchEvent.call(window, new UIEvent("resize"));
  176. dispatchEvent.call(window, new UIEvent("scroll"));
  177. document.documentElement.style.setProperty("transform", transform, transformPriority);
  178. document.documentElement.style.setProperty("transform-origin", transformOrigin, transformOriginPriority);
  179. }
  180. dispatchEvent.call(window, new UIEvent("resize"));
  181. dispatchEvent.call(window, new UIEvent("scroll"));
  182. const docBoundingRect = scrollingElement.getBoundingClientRect();
  183. Array.from(observers, ([intersectionObserver, observer]) => {
  184. const rootBoundingRect = observer.options && observer.options.root && observer.options.root.getBoundingClientRect();
  185. const targetElements = observedElements.get(intersectionObserver);
  186. if (targetElements) {
  187. observer.callback(targetElements.map(target => {
  188. const boundingClientRect = target.getBoundingClientRect();
  189. const isIntersecting = true;
  190. const intersectionRatio = 1;
  191. const rootBounds = observer.options && observer.options.root ? rootBoundingRect : docBoundingRect;
  192. const time = 0;
  193. return { target, intersectionRatio, boundingClientRect, intersectionRect: boundingClientRect, isIntersecting, rootBounds, time };
  194. }), intersectionObserver);
  195. }
  196. });
  197. if (pendingRequestAnimationFrameCalls.size) {
  198. Array.from(pendingRequestAnimationFrameCalls).forEach(([id, callback]) => {
  199. cancelAnimationFrame(id);
  200. callback();
  201. });
  202. }
  203. });
  204. addEventListener.call(window, LOAD_DEFERRED_IMAGES_END_EVENT, () => {
  205. const scrollingElement = document.scrollingElement || document.documentElement;
  206. delete scrollingElement.clientHeight;
  207. delete scrollingElement.clientWidth;
  208. delete screen.height;
  209. delete screen.width;
  210. if (window._singleFile_getBoundingClientRect) {
  211. Element.prototype.getBoundingClientRect = window._singleFile_getBoundingClientRect;
  212. window.innerHeight = window._singleFile_innerHeight;
  213. window.innerWidth = window._singleFile_innerWidth;
  214. delete window._singleFile_getBoundingClientRect;
  215. delete window._singleFile_innerHeight;
  216. delete window._singleFile_innerWidth;
  217. }
  218. if (window._singleFileImage) {
  219. delete window.Image;
  220. window.Image = window._singleFileImage;
  221. delete window._singleFileImage;
  222. }
  223. loadDeferredImages = false;
  224. dispatchEvent.call(window, new UIEvent("resize"));
  225. dispatchEvent.call(window, new UIEvent("scroll"));
  226. });
  227. addEventListener.call(window, BLOCK_COOKIES_START_EVENT, () => {
  228. try {
  229. document.__defineGetter__("cookie", () => { throw new Error("document.cookie temporary blocked by SingleFile"); });
  230. } catch (error) {
  231. // ignored
  232. }
  233. });
  234. addEventListener.call(window, BLOCK_COOKIES_END_EVENT, () => {
  235. delete document.cookie;
  236. });
  237. addEventListener.call(window, BLOCK_STORAGE_START_EVENT, () => {
  238. if (!window._singleFile_localStorage) {
  239. window._singleFile_localStorage = window.localStorage;
  240. window.__defineGetter__("localStorage", () => { throw new Error("localStorage temporary blocked by SingleFile"); });
  241. }
  242. if (!window._singleFile_indexedDB) {
  243. window._singleFile_indexedDB = window.indexedDB;
  244. window.__defineGetter__("indexedDB", () => { throw new Error("indexedDB temporary blocked by SingleFile"); });
  245. }
  246. });
  247. addEventListener.call(window, BLOCK_STORAGE_END_EVENT, () => {
  248. if (window._singleFile_localStorage) {
  249. delete window.localStorage;
  250. window.localStorage = window._singleFile_localStorage;
  251. delete window._singleFile_localStorage;
  252. }
  253. if (!window._singleFile_indexedDB) {
  254. delete window.indexedDB;
  255. window.indexedDB = window._singleFile_indexedDB;
  256. delete window._singleFile_indexedDB;
  257. }
  258. });
  259. let warningRequestAnimationFrameDisplayed;
  260. const pendingRequestAnimationFrameCalls = new Map();
  261. let lastTimestamp = 0;
  262. let errorDetected;
  263. window.requestAnimationFrame = function (callback) {
  264. if (!warningRequestAnimationFrameDisplayed) {
  265. warn.call(console, "SingleFile is hooking the requestAnimationFrame and cancelAnimationFrame functions to load deferred images in background tabs."); // eslint-disable-line no-console
  266. warningRequestAnimationFrameDisplayed = true;
  267. }
  268. let requestId;
  269. if (loadDeferredImages && !errorDetected) {
  270. try {
  271. requestId = 0;
  272. callback(lastTimestamp);
  273. } catch (error) {
  274. errorDetected = true;
  275. requestId = requestAnimationFrame(timestamp => {
  276. lastTimestamp = timestamp;
  277. callback(timestamp);
  278. });
  279. }
  280. } else {
  281. if (!loadDeferredImages) {
  282. errorDetected = false;
  283. }
  284. requestId = requestAnimationFrame(timestamp => {
  285. pendingRequestAnimationFrameCalls.delete(requestId);
  286. lastTimestamp = timestamp;
  287. callback(timestamp);
  288. });
  289. if (!loadDeferredImages || pendingRequestAnimationFrameCalls.length < 128) {
  290. pendingRequestAnimationFrameCalls.set(requestId, callback);
  291. }
  292. }
  293. return requestId;
  294. };
  295. window.requestAnimationFrame.toString = function () { return "requestAnimationFrame() { [native code] }"; };
  296. window.cancelAnimationFrame = function (requestId) {
  297. pendingRequestAnimationFrameCalls.delete(requestId);
  298. return cancelAnimationFrame(requestId);
  299. };
  300. window.cancelAnimationFrame.toString = function () { return "cancelAnimationFrame() { [native code] }"; };
  301. if (window.FontFace) {
  302. const FontFace = window.FontFace;
  303. let warningFontFaceDisplayed;
  304. window.FontFace = function () {
  305. if (!warningFontFaceDisplayed) {
  306. warn.call(console, "SingleFile is hooking the FontFace constructor to get font URLs."); // eslint-disable-line no-console
  307. warningFontFaceDisplayed = true;
  308. }
  309. const detail = {};
  310. detail["font-family"] = arguments[0];
  311. detail.src = arguments[1];
  312. const descriptors = arguments[2];
  313. if (descriptors) {
  314. Object.keys(descriptors).forEach(descriptor => {
  315. if (FONT_STYLE_PROPERTIES[descriptor]) {
  316. detail[FONT_STYLE_PROPERTIES[descriptor]] = descriptors[descriptor];
  317. }
  318. });
  319. }
  320. if (detail.src instanceof ArrayBuffer) {
  321. const reader = new FileReader();
  322. reader.readAsDataURL(new Blob([detail.src]));
  323. reader.addEventListener("load", () => {
  324. detail.src = "url(" + reader.result + ")";
  325. dispatchEvent.call(window, new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  326. });
  327. } else {
  328. dispatchEvent.call(window, new CustomEvent(NEW_FONT_FACE_EVENT, { detail }));
  329. }
  330. return new FontFace(...arguments);
  331. };
  332. window.FontFace.toString = function () { return "function FontFace() { [native code] }"; };
  333. }
  334. if (window.IntersectionObserver) {
  335. const IntersectionObserver = window.IntersectionObserver;
  336. let warningIntersectionObserverDisplayed;
  337. window.IntersectionObserver = function () {
  338. if (!warningIntersectionObserverDisplayed) {
  339. warn.call(console, "SingleFile is hooking the IntersectionObserver API to detect and load deferred images."); // eslint-disable-line no-console
  340. warningIntersectionObserverDisplayed = true;
  341. }
  342. const intersectionObserver = new IntersectionObserver(...arguments);
  343. const observeIntersection = IntersectionObserver.prototype.observe || intersectionObserver.observe;
  344. const unobserveIntersection = IntersectionObserver.prototype.unobserve || intersectionObserver.unobserve;
  345. const callback = arguments[0];
  346. const options = arguments[1];
  347. if (observeIntersection) {
  348. intersectionObserver.observe = function (targetElement) {
  349. let targetElements = observedElements.get(intersectionObserver);
  350. if (!targetElements) {
  351. targetElements = [];
  352. observedElements.set(intersectionObserver, targetElements);
  353. }
  354. targetElements.push(targetElement);
  355. return observeIntersection.call(intersectionObserver, targetElement);
  356. };
  357. }
  358. if (unobserveIntersection) {
  359. intersectionObserver.unobserve = function (targetElement) {
  360. let targetElements = observedElements.get(intersectionObserver);
  361. if (targetElements) {
  362. targetElements = targetElements.filter(element => element != targetElement);
  363. if (targetElements.length) {
  364. observedElements.set(intersectionObserver, targetElements);
  365. } else {
  366. observedElements.delete(intersectionObserver);
  367. observers.delete(intersectionObserver);
  368. }
  369. }
  370. return unobserveIntersection.call(intersectionObserver, targetElement);
  371. };
  372. }
  373. observers.set(intersectionObserver, { callback, options });
  374. return intersectionObserver;
  375. };
  376. window.IntersectionObserver.toString = function () { return "function IntersectionObserver() { [native code] }"; };
  377. }
  378. }
  379. })();