content-hooks-frames-web.js 13 KB

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