| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.singlefile = {}));
- })(this, (function (exports) { 'use strict';
- /*
- * Copyright 2010-2022 Gildas Lormeau
- * contact : gildas.lormeau <at> gmail.com
- *
- * This file is part of SingleFile.
- *
- * The code in this file is free software: you can redistribute it and/or
- * modify it under the terms of the GNU Affero General Public License
- * (GNU AGPL) as published by the Free Software Foundation, either version 3
- * of the License, or (at your option) any later version.
- *
- * The code in this file is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
- * General Public License for more details.
- *
- * As additional permission under GNU AGPL version 3 section 7, you may
- * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
- * AGPL normally required by section 4, provided you include this license
- * notice and a URL through which recipients can access the Corresponding
- * Source.
- */
- /* global globalThis, window */
- const LOAD_DEFERRED_IMAGES_START_EVENT = "single-file-load-deferred-images-start";
- const LOAD_DEFERRED_IMAGES_END_EVENT = "single-file-load-deferred-images-end";
- const LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_START_EVENT = "single-file-load-deferred-images-keep-zoom-level-start";
- const LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT = "single-file-load-deferred-images-keep-zoom-level-end";
- const BLOCK_COOKIES_START_EVENT = "single-file-block-cookies-start";
- const BLOCK_COOKIES_END_EVENT = "single-file-block-cookies-end";
- const DISPATCH_SCROLL_START_EVENT = "single-file-dispatch-scroll-event-start";
- const DISPATCH_SCROLL_END_EVENT = "single-file-dispatch-scroll-event-end";
- const BLOCK_STORAGE_START_EVENT = "single-file-block-storage-start";
- const BLOCK_STORAGE_END_EVENT = "single-file-block-storage-end";
- const LOAD_IMAGE_EVENT = "single-file-load-image";
- const IMAGE_LOADED_EVENT = "single-file-image-loaded";
- const NEW_FONT_FACE_EVENT = "single-file-new-font-face";
- const DELETE_FONT_EVENT = "single-file-delete-font";
- const CLEAR_FONTS_EVENT = "single-file-clear-fonts";
- const FONT_FACE_PROPERTY_NAME = "_singleFile_fontFaces";
- const addEventListener$2 = (type, listener, options) => globalThis.addEventListener(type, listener, options);
- const dispatchEvent = event => { try { globalThis.dispatchEvent(event); } catch (error) { /* ignored */ } };
- const CustomEvent$1 = globalThis.CustomEvent;
- const document$2 = globalThis.document;
- const Document = globalThis.Document;
- const JSON$2 = globalThis.JSON;
- let fontFaces;
- if (window[FONT_FACE_PROPERTY_NAME]) {
- fontFaces = window[FONT_FACE_PROPERTY_NAME];
- } else {
- fontFaces = window[FONT_FACE_PROPERTY_NAME] = new Map();
- }
- if (document$2 instanceof Document) {
- addEventListener$2(NEW_FONT_FACE_EVENT, event => {
- const detail = event.detail;
- const key = Object.assign({}, detail);
- delete key.src;
- fontFaces.set(JSON$2.stringify(key), detail);
- });
- addEventListener$2(DELETE_FONT_EVENT, event => {
- const detail = event.detail;
- const key = Object.assign({}, detail);
- delete key.src;
- fontFaces.delete(JSON$2.stringify(key));
- });
- addEventListener$2(CLEAR_FONTS_EVENT, () => fontFaces = new Map());
- }
- function getFontsData$1() {
- return Array.from(fontFaces.values());
- }
- function loadDeferredImagesStart(options) {
- if (options.loadDeferredImagesBlockCookies) {
- dispatchEvent(new CustomEvent$1(BLOCK_COOKIES_START_EVENT));
- }
- if (options.loadDeferredImagesBlockStorage) {
- dispatchEvent(new CustomEvent$1(BLOCK_STORAGE_START_EVENT));
- }
- if (options.loadDeferredImagesDispatchScrollEvent) {
- dispatchEvent(new CustomEvent$1(DISPATCH_SCROLL_START_EVENT));
- }
- if (options.loadDeferredImagesKeepZoomLevel) {
- dispatchEvent(new CustomEvent$1(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_START_EVENT));
- } else {
- dispatchEvent(new CustomEvent$1(LOAD_DEFERRED_IMAGES_START_EVENT));
- }
- }
- function loadDeferredImagesEnd(options) {
- if (options.loadDeferredImagesBlockCookies) {
- dispatchEvent(new CustomEvent$1(BLOCK_COOKIES_END_EVENT));
- }
- if (options.loadDeferredImagesBlockStorage) {
- dispatchEvent(new CustomEvent$1(BLOCK_STORAGE_END_EVENT));
- }
- if (options.loadDeferredImagesDispatchScrollEvent) {
- dispatchEvent(new CustomEvent$1(DISPATCH_SCROLL_END_EVENT));
- }
- if (options.loadDeferredImagesKeepZoomLevel) {
- dispatchEvent(new CustomEvent$1(LOAD_DEFERRED_IMAGES_KEEP_ZOOM_LEVEL_END_EVENT));
- } else {
- dispatchEvent(new CustomEvent$1(LOAD_DEFERRED_IMAGES_END_EVENT));
- }
- }
- /*
- * The MIT License (MIT)
- *
- * Author: Gildas Lormeau
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- */
- // derived from https://github.com/postcss/postcss-selector-parser/blob/master/src/util/unesc.js
- /*
- * The MIT License (MIT)
- * Copyright (c) Ben Briggs <beneb.info@gmail.com> (http://beneb.info)
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
- const whitespace = "[\\x20\\t\\r\\n\\f]";
- const unescapeRegExp = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig");
- function process$1(str) {
- return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => {
- const high = "0x" + escaped - 0x10000;
- // NaN means non-codepoint
- // Workaround erroneous numeric interpretation of +"0x"
- // eslint-disable-next-line no-self-compare
- return high !== high || escapedWhitespace
- ? escaped
- : high < 0
- ? // BMP codepoint
- String.fromCharCode(high + 0x10000)
- : // Supplemental Plane codepoint (surrogate pair)
- String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
- });
- }
- const SINGLE_FILE_PREFIX = "single-file-";
- const WAIT_FOR_USERSCRIPT_PROPERTY_NAME = "_singleFile_waitForUserScript";
- const MESSAGE_PREFIX = "__frameTree__::";
- /*
- * Copyright 2010-2022 Gildas Lormeau
- * contact : gildas.lormeau <at> gmail.com
- *
- * This file is part of SingleFile.
- *
- * The code in this file is free software: you can redistribute it and/or
- * modify it under the terms of the GNU Affero General Public License
- * (GNU AGPL) as published by the Free Software Foundation, either version 3
- * of the License, or (at your option) any later version.
- *
- * The code in this file is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
- * General Public License for more details.
- *
- * As additional permission under GNU AGPL version 3 section 7, you may
- * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
- * AGPL normally required by section 4, provided you include this license
- * notice and a URL through which recipients can access the Corresponding
- * Source.
- */
- const ON_BEFORE_CAPTURE_EVENT_NAME = SINGLE_FILE_PREFIX + "on-before-capture";
- const ON_AFTER_CAPTURE_EVENT_NAME = SINGLE_FILE_PREFIX + "on-after-capture";
- const GET_ADOPTED_STYLESHEETS_REQUEST_EVENT = SINGLE_FILE_PREFIX + "request-get-adopted-stylesheets";
- const GET_ADOPTED_STYLESHEETS_RESPONSE_EVENT = SINGLE_FILE_PREFIX + "response-get-adopted-stylesheets";
- const UNREGISTER_GET_ADOPTED_STYLESHEETS_REQUEST_EVENT = SINGLE_FILE_PREFIX + "unregister-request-get-adopted-stylesheets";
- const REMOVED_CONTENT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "removed-content";
- const HIDDEN_CONTENT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "hidden-content";
- const KEPT_CONTENT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "kept-content";
- const HIDDEN_FRAME_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "hidden-frame";
- const PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "preserved-space-element";
- const SHADOW_ROOT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "shadow-root-element";
- const WIN_ID_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "win-id";
- const IMAGE_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "image";
- const POSTER_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "poster";
- const VIDEO_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "video";
- const CANVAS_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "canvas";
- const STYLE_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "movable-style";
- const INPUT_VALUE_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "input-value";
- const LAZY_SRC_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "lazy-loaded-src";
- const STYLESHEET_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "stylesheet";
- const DISABLED_NOSCRIPT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "disabled-noscript";
- const INVALID_ELEMENT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "invalid-element";
- const ASYNC_SCRIPT_ATTRIBUTE_NAME = "data-" + SINGLE_FILE_PREFIX + "async-script";
- const FLOW_ELEMENTS_SELECTOR = "*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)";
- const KEPT_TAG_NAMES = ["NOSCRIPT", "DISABLED-NOSCRIPT", "META", "LINK", "STYLE", "TITLE", "TEMPLATE", "SOURCE", "OBJECT", "SCRIPT", "HEAD", "BODY"];
- const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
- const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
- const FONT_WEIGHTS = {
- regular: "400",
- normal: "400",
- bold: "700",
- bolder: "700",
- lighter: "100"
- };
- const SINGLE_FILE_UI_ELEMENT_CLASS = "single-file-ui-element";
- const EMPTY_RESOURCE = "data:,";
- const JSON$1 = globalThis.JSON;
- function initDoc(doc) {
- doc.querySelectorAll("meta[http-equiv=refresh]").forEach(element => {
- element.removeAttribute("http-equiv");
- element.setAttribute("disabled-http-equiv", "refresh");
- });
- }
- function preProcessDoc(doc, win, options) {
- doc.querySelectorAll("noscript:not([" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "])").forEach(element => {
- element.setAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME, element.textContent);
- element.textContent = "";
- });
- initDoc(doc);
- if (doc.head) {
- doc.head.querySelectorAll(FLOW_ELEMENTS_SELECTOR).forEach(element => element.hidden = true);
- }
- doc.querySelectorAll("svg foreignObject").forEach(element => {
- const flowElements = element.querySelectorAll("html > head > " + FLOW_ELEMENTS_SELECTOR + ", html > body > " + FLOW_ELEMENTS_SELECTOR);
- if (flowElements.length) {
- Array.from(element.childNodes).forEach(node => node.remove());
- flowElements.forEach(flowElement => element.appendChild(flowElement));
- }
- });
- const invalidElements = new Map();
- let elementsInfo;
- if (win && doc.documentElement) {
- doc.querySelectorAll("button button, a a").forEach(element => {
- const placeHolderElement = doc.createElement("template");
- placeHolderElement.setAttribute(INVALID_ELEMENT_ATTRIBUTE_NAME, "");
- placeHolderElement.content.appendChild(element.cloneNode(true));
- invalidElements.set(element, placeHolderElement);
- element.replaceWith(placeHolderElement);
- });
- elementsInfo = getElementsInfo(win, doc, doc.documentElement, options);
- if (options.moveStylesInHead) {
- doc.querySelectorAll("body style, body ~ style").forEach(element => {
- const computedStyle = getComputedStyle(win, element);
- if (computedStyle && testHiddenElement(element, computedStyle)) {
- element.setAttribute(STYLE_ATTRIBUTE_NAME, "");
- elementsInfo.markedElements.push(element);
- }
- });
- }
- } else {
- elementsInfo = {
- canvases: [],
- images: [],
- posters: [],
- videos: [],
- usedFonts: [],
- shadowRoots: [],
- markedElements: []
- };
- }
- return {
- canvases: elementsInfo.canvases,
- fonts: getFontsData(),
- stylesheets: getStylesheetsData(doc),
- images: elementsInfo.images,
- posters: elementsInfo.posters,
- videos: elementsInfo.videos,
- usedFonts: Array.from(elementsInfo.usedFonts.values()),
- shadowRoots: elementsInfo.shadowRoots,
- referrer: doc.referrer,
- markedElements: elementsInfo.markedElements,
- invalidElements,
- scrollPosition: { x: win.scrollX, y: win.scrollY },
- adoptedStyleSheets: getStylesheetsContent(doc.adoptedStyleSheets)
- };
- }
- function getElementsInfo(win, doc, element, options, data = { usedFonts: new Map(), canvases: [], images: [], posters: [], videos: [], shadowRoots: [], markedElements: [] }, ascendantHidden) {
- if (element.childNodes) {
- const elements = Array.from(element.childNodes).filter(node => (node instanceof win.HTMLElement) || (node instanceof win.SVGElement));
- elements.forEach(element => {
- let elementHidden, elementKept, computedStyle;
- if (!options.autoSaveExternalSave && (options.removeHiddenElements || options.removeUnusedFonts || options.compressHTML)) {
- computedStyle = getComputedStyle(win, element);
- if (element instanceof win.HTMLElement) {
- if (options.removeHiddenElements) {
- elementKept = ((ascendantHidden || element.closest("html > head")) && KEPT_TAG_NAMES.includes(element.tagName.toUpperCase())) || element.closest("details");
- if (!elementKept) {
- elementHidden = ascendantHidden || testHiddenElement(element, computedStyle);
- if (elementHidden) {
- element.setAttribute(HIDDEN_CONTENT_ATTRIBUTE_NAME, "");
- data.markedElements.push(element);
- }
- }
- }
- }
- if (!elementHidden) {
- if (options.compressHTML && computedStyle) {
- const whiteSpace = computedStyle.getPropertyValue("white-space");
- if (whiteSpace && whiteSpace.startsWith("pre")) {
- element.setAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, "");
- data.markedElements.push(element);
- }
- }
- if (options.removeUnusedFonts) {
- getUsedFont(computedStyle, options, data.usedFonts);
- getUsedFont(getComputedStyle(win, element, ":first-letter"), options, data.usedFonts);
- getUsedFont(getComputedStyle(win, element, ":before"), options, data.usedFonts);
- getUsedFont(getComputedStyle(win, element, ":after"), options, data.usedFonts);
- }
- }
- }
- getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle);
- const shadowRoot = !(element instanceof win.SVGElement) && getShadowRoot(element);
- if (shadowRoot && !element.classList.contains(SINGLE_FILE_UI_ELEMENT_CLASS)) {
- const shadowRootInfo = {};
- element.setAttribute(SHADOW_ROOT_ATTRIBUTE_NAME, data.shadowRoots.length);
- data.markedElements.push(element);
- data.shadowRoots.push(shadowRootInfo);
- try {
- if (shadowRoot.adoptedStyleSheets) {
- if (shadowRoot.adoptedStyleSheets.length) {
- shadowRootInfo.adoptedStyleSheets = getStylesheetsContent(shadowRoot.adoptedStyleSheets);
- } else if (shadowRoot.adoptedStyleSheets.length === undefined) {
- const listener = event => shadowRootInfo.adoptedStyleSheets = event.detail.adoptedStyleSheets;
- element.addEventListener(GET_ADOPTED_STYLESHEETS_RESPONSE_EVENT, listener);
- element.dispatchEvent(new CustomEvent(GET_ADOPTED_STYLESHEETS_REQUEST_EVENT, { bubbles: true }));
- element.removeEventListener(GET_ADOPTED_STYLESHEETS_RESPONSE_EVENT, listener);
- }
- }
- } catch (error) {
- // ignored
- }
- getElementsInfo(win, doc, shadowRoot, options, data, elementHidden);
- shadowRootInfo.content = shadowRoot.innerHTML;
- shadowRootInfo.mode = shadowRoot.mode;
- try {
- if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length === undefined) {
- element.dispatchEvent(new CustomEvent(UNREGISTER_GET_ADOPTED_STYLESHEETS_REQUEST_EVENT, { bubbles: true }));
- }
- } catch (error) {
- // ignored
- }
- }
- getElementsInfo(win, doc, element, options, data, elementHidden);
- if (!options.autoSaveExternalSave && options.removeHiddenElements && ascendantHidden) {
- if (elementKept || element.getAttribute(KEPT_CONTENT_ATTRIBUTE_NAME) == "") {
- if (element.parentElement) {
- element.parentElement.setAttribute(KEPT_CONTENT_ATTRIBUTE_NAME, "");
- data.markedElements.push(element.parentElement);
- }
- } else if (elementHidden) {
- element.setAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME, "");
- data.markedElements.push(element);
- }
- }
- });
- }
- return data;
- }
- function getStylesheetsContent(styleSheets) {
- return styleSheets ? Array.from(styleSheets).map(stylesheet => Array.from(stylesheet.cssRules).map(cssRule => cssRule.cssText).join("\n")) : [];
- }
- function getResourcesInfo(win, doc, element, options, data, elementHidden, computedStyle) {
- const tagName = element.tagName && element.tagName.toUpperCase();
- if (tagName == "CANVAS") {
- try {
- data.canvases.push({
- dataURI: element.toDataURL("image/png", ""),
- backgroundColor: computedStyle.getPropertyValue("background-color")
- });
- element.setAttribute(CANVAS_ATTRIBUTE_NAME, data.canvases.length - 1);
- data.markedElements.push(element);
- } catch (error) {
- // ignored
- }
- }
- if (tagName == "IMG") {
- const imageData = {
- currentSrc: elementHidden ?
- EMPTY_RESOURCE :
- (options.loadDeferredImages && element.getAttribute(LAZY_SRC_ATTRIBUTE_NAME)) || element.currentSrc
- };
- data.images.push(imageData);
- element.setAttribute(IMAGE_ATTRIBUTE_NAME, data.images.length - 1);
- data.markedElements.push(element);
- element.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
- computedStyle = computedStyle || getComputedStyle(win, element);
- if (computedStyle) {
- imageData.size = getSize(win, element, computedStyle);
- const boxShadow = computedStyle.getPropertyValue("box-shadow");
- const backgroundImage = computedStyle.getPropertyValue("background-image");
- if ((!boxShadow || boxShadow == "none") &&
- (!backgroundImage || backgroundImage == "none") &&
- (imageData.size.pxWidth > 1 || imageData.size.pxHeight > 1)) {
- imageData.replaceable = true;
- imageData.backgroundColor = computedStyle.getPropertyValue("background-color");
- imageData.objectFit = computedStyle.getPropertyValue("object-fit");
- imageData.boxSizing = computedStyle.getPropertyValue("box-sizing");
- imageData.objectPosition = computedStyle.getPropertyValue("object-position");
- }
- }
- }
- if (tagName == "VIDEO") {
- const src = element.currentSrc;
- if (src && !src.startsWith("blob:") && !src.startsWith("data:")) {
- const computedStyle = getComputedStyle(win, element.parentNode);
- data.videos.push({
- positionParent: computedStyle && computedStyle.getPropertyValue("position"),
- src,
- size: {
- pxWidth: element.clientWidth,
- pxHeight: element.clientHeight
- },
- currentTime: element.currentTime
- });
- element.setAttribute(VIDEO_ATTRIBUTE_NAME, data.videos.length - 1);
- }
- if (!element.getAttribute("poster")) {
- const canvasElement = doc.createElement("canvas");
- const context = canvasElement.getContext("2d");
- canvasElement.width = element.clientWidth;
- canvasElement.height = element.clientHeight;
- try {
- context.drawImage(element, 0, 0, canvasElement.width, canvasElement.height);
- data.posters.push(canvasElement.toDataURL("image/png", ""));
- element.setAttribute(POSTER_ATTRIBUTE_NAME, data.posters.length - 1);
- data.markedElements.push(element);
- } catch (error) {
- // ignored
- }
- }
- }
- if (tagName == "IFRAME") {
- if (elementHidden && options.removeHiddenElements) {
- element.setAttribute(HIDDEN_FRAME_ATTRIBUTE_NAME, "");
- data.markedElements.push(element);
- }
- }
- if (tagName == "INPUT") {
- if (element.type != "password") {
- element.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, element.value);
- data.markedElements.push(element);
- }
- if (element.type == "radio" || element.type == "checkbox") {
- element.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, element.checked);
- data.markedElements.push(element);
- }
- }
- if (tagName == "TEXTAREA") {
- element.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, element.value);
- data.markedElements.push(element);
- }
- if (tagName == "SELECT") {
- element.querySelectorAll("option").forEach(option => {
- if (option.selected) {
- option.setAttribute(INPUT_VALUE_ATTRIBUTE_NAME, "");
- data.markedElements.push(option);
- }
- });
- }
- if (tagName == "SCRIPT") {
- if (element.async && element.getAttribute("async") != "" && element.getAttribute("async") != "async") {
- element.setAttribute(ASYNC_SCRIPT_ATTRIBUTE_NAME, "");
- data.markedElements.push(element);
- }
- element.textContent = element.textContent.replace(/<\/script>/gi, "<\\/script>");
- }
- }
- function getUsedFont(computedStyle, options, usedFonts) {
- if (computedStyle) {
- const fontStyle = computedStyle.getPropertyValue("font-style") || "normal";
- computedStyle.getPropertyValue("font-family").split(",").forEach(fontFamilyName => {
- fontFamilyName = normalizeFontFamily(fontFamilyName);
- if (!options.loadedFonts || options.loadedFonts.find(font => normalizeFontFamily(font.family) == fontFamilyName && font.style == fontStyle)) {
- const fontWeight = getFontWeight(computedStyle.getPropertyValue("font-weight"));
- const fontVariant = computedStyle.getPropertyValue("font-variant") || "normal";
- const value = [fontFamilyName, fontWeight, fontStyle, fontVariant];
- usedFonts.set(JSON$1.stringify(value), [fontFamilyName, fontWeight, fontStyle, fontVariant]);
- }
- });
- }
- }
- function getShadowRoot(element) {
- const chrome = globalThis.chrome;
- if (element.openOrClosedShadowRoot) {
- return element.openOrClosedShadowRoot;
- } else if (chrome && chrome.dom && chrome.dom.openOrClosedShadowRoot) {
- try {
- return chrome.dom.openOrClosedShadowRoot(element);
- } catch (error) {
- return element.shadowRoot;
- }
- } else {
- return element.shadowRoot;
- }
- }
- function normalizeFontFamily(fontFamilyName = "") {
- return removeQuotes(process$1(fontFamilyName.trim())).toLowerCase();
- }
- function testHiddenElement(element, computedStyle) {
- let hidden = false;
- if (computedStyle) {
- const display = computedStyle.getPropertyValue("display");
- const opacity = computedStyle.getPropertyValue("opacity");
- const visibility = computedStyle.getPropertyValue("visibility");
- hidden = display == "none";
- if (!hidden && (opacity == "0" || visibility == "hidden") && element.getBoundingClientRect) {
- const boundingRect = element.getBoundingClientRect();
- hidden = !boundingRect.width && !boundingRect.height;
- }
- }
- return Boolean(hidden);
- }
- function postProcessDoc(doc, markedElements, invalidElements) {
- doc.querySelectorAll("[" + DISABLED_NOSCRIPT_ATTRIBUTE_NAME + "]").forEach(element => {
- element.textContent = element.getAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
- element.removeAttribute(DISABLED_NOSCRIPT_ATTRIBUTE_NAME);
- if (doc.body.firstChild) {
- doc.body.insertBefore(element, doc.body.firstChild);
- } else {
- doc.body.appendChild(element);
- }
- });
- doc.querySelectorAll("meta[disabled-http-equiv]").forEach(element => {
- element.setAttribute("http-equiv", element.getAttribute("disabled-http-equiv"));
- element.removeAttribute("disabled-http-equiv");
- });
- if (doc.head) {
- doc.head.querySelectorAll("*:not(base):not(link):not(meta):not(noscript):not(script):not(style):not(template):not(title)").forEach(element => element.removeAttribute("hidden"));
- }
- if (!markedElements) {
- const singleFileAttributes = [REMOVED_CONTENT_ATTRIBUTE_NAME, HIDDEN_FRAME_ATTRIBUTE_NAME, HIDDEN_CONTENT_ATTRIBUTE_NAME, PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME, IMAGE_ATTRIBUTE_NAME, POSTER_ATTRIBUTE_NAME, VIDEO_ATTRIBUTE_NAME, CANVAS_ATTRIBUTE_NAME, INPUT_VALUE_ATTRIBUTE_NAME, SHADOW_ROOT_ATTRIBUTE_NAME, STYLESHEET_ATTRIBUTE_NAME, ASYNC_SCRIPT_ATTRIBUTE_NAME];
- markedElements = doc.querySelectorAll(singleFileAttributes.map(name => "[" + name + "]").join(","));
- }
- markedElements.forEach(element => {
- element.removeAttribute(REMOVED_CONTENT_ATTRIBUTE_NAME);
- element.removeAttribute(HIDDEN_CONTENT_ATTRIBUTE_NAME);
- element.removeAttribute(KEPT_CONTENT_ATTRIBUTE_NAME);
- element.removeAttribute(HIDDEN_FRAME_ATTRIBUTE_NAME);
- element.removeAttribute(PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME);
- element.removeAttribute(IMAGE_ATTRIBUTE_NAME);
- element.removeAttribute(POSTER_ATTRIBUTE_NAME);
- element.removeAttribute(VIDEO_ATTRIBUTE_NAME);
- element.removeAttribute(CANVAS_ATTRIBUTE_NAME);
- element.removeAttribute(INPUT_VALUE_ATTRIBUTE_NAME);
- element.removeAttribute(SHADOW_ROOT_ATTRIBUTE_NAME);
- element.removeAttribute(STYLESHEET_ATTRIBUTE_NAME);
- element.removeAttribute(ASYNC_SCRIPT_ATTRIBUTE_NAME);
- element.removeAttribute(STYLE_ATTRIBUTE_NAME);
- });
- if (invalidElements) {
- invalidElements.forEach((placeholderElement, element) => placeholderElement.replaceWith(element));
- }
- }
- function getStylesheetsData(doc) {
- if (doc) {
- const contents = [];
- doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
- try {
- const tempStyleElement = doc.createElement("style");
- tempStyleElement.textContent = styleElement.textContent;
- doc.body.appendChild(tempStyleElement);
- const stylesheet = tempStyleElement.sheet;
- tempStyleElement.remove();
- if (!stylesheet || stylesheet.cssRules.length != styleElement.sheet.cssRules.length) {
- styleElement.setAttribute(STYLESHEET_ATTRIBUTE_NAME, styleIndex);
- contents[styleIndex] = Array.from(styleElement.sheet.cssRules).map(cssRule => cssRule.cssText).join("\n");
- }
- } catch (error) {
- // ignored
- }
- });
- return contents;
- }
- }
- function getSize(win, imageElement, computedStyle) {
- let pxWidth = imageElement.naturalWidth;
- let pxHeight = imageElement.naturalHeight;
- if (!pxWidth && !pxHeight) {
- const noStyleAttribute = imageElement.getAttribute("style") == null;
- computedStyle = computedStyle || getComputedStyle(win, imageElement);
- if (computedStyle) {
- let removeBorderWidth = false;
- if (computedStyle.getPropertyValue("box-sizing") == "content-box") {
- const boxSizingValue = imageElement.style.getPropertyValue("box-sizing");
- const boxSizingPriority = imageElement.style.getPropertyPriority("box-sizing");
- const clientWidth = imageElement.clientWidth;
- imageElement.style.setProperty("box-sizing", "border-box", "important");
- removeBorderWidth = imageElement.clientWidth != clientWidth;
- if (boxSizingValue) {
- imageElement.style.setProperty("box-sizing", boxSizingValue, boxSizingPriority);
- } else {
- imageElement.style.removeProperty("box-sizing");
- }
- }
- let paddingLeft, paddingRight, paddingTop, paddingBottom, borderLeft, borderRight, borderTop, borderBottom;
- paddingLeft = getWidth("padding-left", computedStyle);
- paddingRight = getWidth("padding-right", computedStyle);
- paddingTop = getWidth("padding-top", computedStyle);
- paddingBottom = getWidth("padding-bottom", computedStyle);
- if (removeBorderWidth) {
- borderLeft = getWidth("border-left-width", computedStyle);
- borderRight = getWidth("border-right-width", computedStyle);
- borderTop = getWidth("border-top-width", computedStyle);
- borderBottom = getWidth("border-bottom-width", computedStyle);
- } else {
- borderLeft = borderRight = borderTop = borderBottom = 0;
- }
- pxWidth = Math.max(0, imageElement.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight);
- pxHeight = Math.max(0, imageElement.clientHeight - paddingTop - paddingBottom - borderTop - borderBottom);
- if (noStyleAttribute) {
- imageElement.removeAttribute("style");
- }
- }
- }
- return { pxWidth, pxHeight };
- }
- function getWidth(styleName, computedStyle) {
- if (computedStyle.getPropertyValue(styleName).endsWith("px")) {
- return parseFloat(computedStyle.getPropertyValue(styleName));
- }
- }
- function getFontsData() {
- return getFontsData$1();
- }
- function serialize(doc) {
- const docType = doc.doctype;
- let docTypeString = "";
- if (docType) {
- docTypeString = "<!DOCTYPE " + docType.nodeName;
- if (docType.publicId) {
- docTypeString += " PUBLIC \"" + docType.publicId + "\"";
- if (docType.systemId) {
- docTypeString += " \"" + docType.systemId + "\"";
- }
- } else if (docType.systemId) {
- docTypeString += " SYSTEM \"" + docType.systemId + "\"";
- } if (docType.internalSubset) {
- docTypeString += " [" + docType.internalSubset + "]";
- }
- docTypeString += "> ";
- }
- return docTypeString + doc.documentElement.outerHTML;
- }
- function removeQuotes(string) {
- if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
- string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
- } else {
- string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
- }
- return string.trim();
- }
- function getFontWeight(weight) {
- return FONT_WEIGHTS[weight.toLowerCase().trim()] || weight;
- }
- function getComputedStyle(win, element, pseudoElement) {
- try {
- return win.getComputedStyle(element, pseudoElement);
- } catch (error) {
- // ignored
- }
- }
- /*
- * Copyright 2010-2022 Gildas Lormeau
- * contact : gildas.lormeau <at> gmail.com
- *
- * This file is part of SingleFile.
- *
- * The code in this file is free software: you can redistribute it and/or
- * modify it under the terms of the GNU Affero General Public License
- * (GNU AGPL) as published by the Free Software Foundation, either version 3
- * of the License, or (at your option) any later version.
- *
- * The code in this file is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
- * General Public License for more details.
- *
- * As additional permission under GNU AGPL version 3 section 7, you may
- * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
- * AGPL normally required by section 4, provided you include this license
- * notice and a URL through which recipients can access the Corresponding
- * Source.
- */
- const helper$1 = {
- LAZY_SRC_ATTRIBUTE_NAME,
- SINGLE_FILE_UI_ELEMENT_CLASS
- };
- const MAX_IDLE_TIMEOUT_CALLS = 10;
- const ATTRIBUTES_MUTATION_TYPE = "attributes";
- const browser$1 = globalThis.browser;
- const document$1 = globalThis.document;
- const MutationObserver = globalThis.MutationObserver;
- const addEventListener$1 = (type, listener, options) => globalThis.addEventListener(type, listener, options);
- const removeEventListener = (type, listener, options) => globalThis.removeEventListener(type, listener, options);
- const timeouts = new Map();
- let idleTimeoutCalls;
- if (browser$1 && browser$1.runtime && browser$1.runtime.onMessage && browser$1.runtime.onMessage.addListener) {
- browser$1.runtime.onMessage.addListener(message => {
- if (message.method == "singlefile.lazyTimeout.onTimeout") {
- const timeoutData = timeouts.get(message.type);
- if (timeoutData) {
- timeouts.delete(message.type);
- try {
- timeoutData.callback();
- } catch (error) {
- clearRegularTimeout(message.type);
- }
- }
- }
- });
- }
- async function process(options) {
- if (document$1.documentElement) {
- timeouts.clear();
- const bodyHeight = document$1.body ? Math.max(document$1.body.scrollHeight, document$1.documentElement.scrollHeight) : document$1.documentElement.scrollHeight;
- const bodyWidth = document$1.body ? Math.max(document$1.body.scrollWidth, document$1.documentElement.scrollWidth) : document$1.documentElement.scrollWidth;
- if (bodyHeight > globalThis.innerHeight || bodyWidth > globalThis.innerWidth) {
- const maxScrollY = Math.max(bodyHeight - (globalThis.innerHeight * 1.5), 0);
- const maxScrollX = Math.max(bodyWidth - (globalThis.innerWidth * 1.5), 0);
- if (globalThis.scrollY < maxScrollY || globalThis.scrollX < maxScrollX) {
- return triggerLazyLoading(options);
- }
- }
- }
- }
- function triggerLazyLoading(options) {
- idleTimeoutCalls = 0;
- return new Promise(async resolve => { // eslint-disable-line no-async-promise-executor
- let loadingImages;
- const pendingImages = new Set();
- const observer = new MutationObserver(async mutations => {
- mutations = mutations.filter(mutation => mutation.type == ATTRIBUTES_MUTATION_TYPE);
- if (mutations.length) {
- const updated = mutations.filter(mutation => {
- if (mutation.attributeName == "src") {
- mutation.target.setAttribute(helper$1.LAZY_SRC_ATTRIBUTE_NAME, mutation.target.src);
- mutation.target.addEventListener("load", onResourceLoad);
- }
- if (mutation.attributeName == "src" || mutation.attributeName == "srcset" ||
- (mutation.target.tagName && mutation.target.tagName.toUpperCase() == "SOURCE")) {
- return !mutation.target.classList || !mutation.target.classList.contains(helper$1.SINGLE_FILE_UI_ELEMENT_CLASS);
- }
- });
- if (updated.length) {
- loadingImages = true;
- await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
- if (!pendingImages.size) {
- await deferLazyLoadEnd(observer, options, cleanupAndResolve);
- }
- }
- }
- });
- await setIdleTimeout(options.loadDeferredImagesMaxIdleTime * 2);
- await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
- observer.observe(document$1, { subtree: true, childList: true, attributes: true });
- addEventListener$1(LOAD_IMAGE_EVENT, onImageLoadEvent);
- addEventListener$1(IMAGE_LOADED_EVENT, onImageLoadedEvent);
- loadDeferredImagesStart(options);
- async function setIdleTimeout(delay) {
- await setAsyncTimeout("idleTimeout", async () => {
- if (!loadingImages) {
- clearAsyncTimeout("loadTimeout");
- clearAsyncTimeout("maxTimeout");
- lazyLoadEnd(observer, options, cleanupAndResolve);
- } else if (idleTimeoutCalls < MAX_IDLE_TIMEOUT_CALLS) {
- idleTimeoutCalls++;
- clearAsyncTimeout("idleTimeout");
- await setIdleTimeout(Math.max(500, delay / 2));
- }
- }, delay, options.loadDeferredImagesNativeTimeout);
- }
- function onResourceLoad(event) {
- const element = event.target;
- element.removeAttribute(helper$1.LAZY_SRC_ATTRIBUTE_NAME);
- element.removeEventListener("load", onResourceLoad);
- }
- async function onImageLoadEvent(event) {
- loadingImages = true;
- await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
- await deferLazyLoadEnd(observer, options, cleanupAndResolve);
- if (event.detail) {
- pendingImages.add(event.detail);
- }
- }
- async function onImageLoadedEvent(event) {
- await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
- await deferLazyLoadEnd(observer, options, cleanupAndResolve);
- pendingImages.delete(event.detail);
- if (!pendingImages.size) {
- await deferLazyLoadEnd(observer, options, cleanupAndResolve);
- }
- }
- function cleanupAndResolve(value) {
- observer.disconnect();
- removeEventListener(LOAD_IMAGE_EVENT, onImageLoadEvent);
- removeEventListener(IMAGE_LOADED_EVENT, onImageLoadedEvent);
- resolve(value);
- }
- });
- }
- async function deferLazyLoadEnd(observer, options, resolve) {
- await setAsyncTimeout("loadTimeout", () => lazyLoadEnd(observer, options, resolve), options.loadDeferredImagesMaxIdleTime, options.loadDeferredImagesNativeTimeout);
- }
- async function deferForceLazyLoadEnd(observer, options, resolve) {
- await setAsyncTimeout("maxTimeout", async () => {
- await clearAsyncTimeout("loadTimeout");
- await lazyLoadEnd(observer, options, resolve);
- }, options.loadDeferredImagesMaxIdleTime * 10, options.loadDeferredImagesNativeTimeout);
- }
- async function lazyLoadEnd(observer, options, resolve) {
- await clearAsyncTimeout("idleTimeout");
- loadDeferredImagesEnd(options);
- await setAsyncTimeout("endTimeout", async () => {
- await clearAsyncTimeout("maxTimeout");
- resolve();
- }, options.loadDeferredImagesMaxIdleTime / 2, options.loadDeferredImagesNativeTimeout);
- observer.disconnect();
- }
- async function setAsyncTimeout(type, callback, delay, forceNativeTimeout) {
- if (browser$1 && browser$1.runtime && browser$1.runtime.sendMessage && !forceNativeTimeout) {
- if (!timeouts.get(type) || !timeouts.get(type).pending) {
- const timeoutData = { callback, pending: true };
- timeouts.set(type, timeoutData);
- try {
- await browser$1.runtime.sendMessage({ method: "singlefile.lazyTimeout.setTimeout", type, delay });
- } catch (error) {
- setRegularTimeout(type, callback, delay);
- }
- timeoutData.pending = false;
- }
- } else {
- setRegularTimeout(type, callback, delay);
- }
- }
- function setRegularTimeout(type, callback, delay) {
- const timeoutId = timeouts.get(type);
- if (timeoutId) {
- globalThis.clearTimeout(timeoutId);
- }
- timeouts.set(type, callback);
- globalThis.setTimeout(callback, delay);
- }
- async function clearAsyncTimeout(type) {
- if (browser$1 && browser$1.runtime && browser$1.runtime.sendMessage) {
- try {
- await browser$1.runtime.sendMessage({ method: "singlefile.lazyTimeout.clearTimeout", type });
- } catch (error) {
- clearRegularTimeout(type);
- }
- } else {
- clearRegularTimeout(type);
- }
- }
- function clearRegularTimeout(type) {
- const previousTimeoutId = timeouts.get(type);
- timeouts.delete(type);
- if (previousTimeoutId) {
- globalThis.clearTimeout(previousTimeoutId);
- }
- }
- /*
- * Copyright 2010-2022 Gildas Lormeau
- * contact : gildas.lormeau <at> gmail.com
- *
- * This file is part of SingleFile.
- *
- * The code in this file is free software: you can redistribute it and/or
- * modify it under the terms of the GNU Affero General Public License
- * (GNU AGPL) as published by the Free Software Foundation, either version 3
- * of the License, or (at your option) any later version.
- *
- * The code in this file is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
- * General Public License for more details.
- *
- * As additional permission under GNU AGPL version 3 section 7, you may
- * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
- * AGPL normally required by section 4, provided you include this license
- * notice and a URL through which recipients can access the Corresponding
- * Source.
- */
- const helper = {
- ON_BEFORE_CAPTURE_EVENT_NAME,
- ON_AFTER_CAPTURE_EVENT_NAME,
- WIN_ID_ATTRIBUTE_NAME,
- WAIT_FOR_USERSCRIPT_PROPERTY_NAME,
- preProcessDoc,
- serialize,
- postProcessDoc,
- getShadowRoot
- };
- const FRAMES_CSS_SELECTOR = "iframe, frame, object[type=\"text/html\"][data]";
- const ALL_ELEMENTS_CSS_SELECTOR = "*";
- const INIT_REQUEST_MESSAGE = "singlefile.frameTree.initRequest";
- const ACK_INIT_REQUEST_MESSAGE = "singlefile.frameTree.ackInitRequest";
- const CLEANUP_REQUEST_MESSAGE = "singlefile.frameTree.cleanupRequest";
- const INIT_RESPONSE_MESSAGE = "singlefile.frameTree.initResponse";
- const TARGET_ORIGIN = "*";
- const TIMEOUT_INIT_REQUEST_MESSAGE = 5000;
- const TIMEOUT_INIT_RESPONSE_MESSAGE = 10000;
- const TOP_WINDOW_ID = "0";
- const WINDOW_ID_SEPARATOR = ".";
- const TOP_WINDOW = globalThis.window == globalThis.top;
- const browser = globalThis.browser;
- const addEventListener = (type, listener, options) => globalThis.addEventListener(type, listener, options);
- const top = globalThis.top;
- const MessageChannel = globalThis.MessageChannel;
- const document = globalThis.document;
- const JSON = globalThis.JSON;
- let sessions = globalThis.sessions;
- if (!sessions) {
- sessions = globalThis.sessions = new Map();
- }
- let windowId;
- if (TOP_WINDOW) {
- windowId = TOP_WINDOW_ID;
- if (browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
- browser.runtime.onMessage.addListener(message => {
- if (message.method == INIT_RESPONSE_MESSAGE) {
- initResponse(message);
- return Promise.resolve({});
- } else if (message.method == ACK_INIT_REQUEST_MESSAGE) {
- clearFrameTimeout("requestTimeouts", message.sessionId, message.windowId);
- createFrameResponseTimeout(message.sessionId, message.windowId);
- return Promise.resolve({});
- }
- });
- }
- }
- addEventListener("message", async event => {
- if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
- event.preventDefault();
- event.stopPropagation();
- const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
- if (message.method == INIT_REQUEST_MESSAGE) {
- if (event.source) {
- sendMessage(event.source, { method: ACK_INIT_REQUEST_MESSAGE, windowId: message.windowId, sessionId: message.sessionId });
- }
- if (!TOP_WINDOW) {
- globalThis.stop();
- if (message.options.loadDeferredImages) {
- process(message.options);
- }
- await initRequestAsync(message);
- }
- } else if (message.method == ACK_INIT_REQUEST_MESSAGE) {
- clearFrameTimeout("requestTimeouts", message.sessionId, message.windowId);
- createFrameResponseTimeout(message.sessionId, message.windowId);
- } else if (message.method == CLEANUP_REQUEST_MESSAGE) {
- cleanupRequest(message);
- } else if (message.method == INIT_RESPONSE_MESSAGE && sessions.get(message.sessionId)) {
- const port = event.ports[0];
- port.onmessage = event => initResponse(event.data);
- }
- }
- }, true);
- function getAsync(options) {
- const sessionId = getNewSessionId();
- options = JSON.parse(JSON.stringify(options));
- return new Promise(resolve => {
- sessions.set(sessionId, {
- frames: [],
- requestTimeouts: {},
- responseTimeouts: {},
- resolve: frames => {
- frames.sessionId = sessionId;
- resolve(frames);
- }
- });
- initRequestAsync({ windowId, sessionId, options });
- });
- }
- function getSync(options) {
- const sessionId = getNewSessionId();
- options = JSON.parse(JSON.stringify(options));
- sessions.set(sessionId, {
- frames: [],
- requestTimeouts: {},
- responseTimeouts: {}
- });
- initRequestSync({ windowId, sessionId, options });
- const frames = sessions.get(sessionId).frames;
- frames.sessionId = sessionId;
- return frames;
- }
- function cleanup(sessionId) {
- sessions.delete(sessionId);
- cleanupRequest({ windowId, sessionId, options: { sessionId } });
- }
- function getNewSessionId() {
- return globalThis.crypto.getRandomValues(new Uint32Array(32)).join("");
- }
- function initRequestSync(message) {
- const sessionId = message.sessionId;
- const waitForUserScript = globalThis[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
- delete globalThis._singleFile_cleaningUp;
- if (!TOP_WINDOW) {
- windowId = globalThis.frameId = message.windowId;
- }
- processFrames(document, message.options, windowId, sessionId);
- if (!TOP_WINDOW) {
- if (message.options.userScriptEnabled && waitForUserScript) {
- waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
- }
- sendInitResponse({ frames: [getFrameData(document, globalThis, windowId, message.options, message.scrolling)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
- if (message.options.userScriptEnabled && waitForUserScript) {
- waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
- }
- delete document.documentElement.dataset.requestedFrameId;
- }
- }
- async function initRequestAsync(message) {
- const sessionId = message.sessionId;
- const waitForUserScript = globalThis[helper.WAIT_FOR_USERSCRIPT_PROPERTY_NAME];
- delete globalThis._singleFile_cleaningUp;
- if (!TOP_WINDOW) {
- windowId = globalThis.frameId = message.windowId;
- }
- processFrames(document, message.options, windowId, sessionId);
- if (!TOP_WINDOW) {
- if (message.options.userScriptEnabled && waitForUserScript) {
- await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
- }
- sendInitResponse({ frames: [getFrameData(document, globalThis, windowId, message.options, message.scrolling)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
- if (message.options.userScriptEnabled && waitForUserScript) {
- await waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
- }
- delete document.documentElement.dataset.requestedFrameId;
- }
- }
- function cleanupRequest(message) {
- if (!globalThis._singleFile_cleaningUp) {
- globalThis._singleFile_cleaningUp = true;
- const sessionId = message.sessionId;
- cleanupFrames(getFrames(document), message.windowId, sessionId);
- }
- }
- function initResponse(message) {
- message.frames.forEach(frameData => clearFrameTimeout("responseTimeouts", message.sessionId, frameData.windowId));
- const windowData = sessions.get(message.sessionId);
- if (windowData) {
- if (message.requestedFrameId) {
- windowData.requestedFrameId = message.requestedFrameId;
- }
- message.frames.forEach(messageFrameData => {
- let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
- if (!frameData) {
- frameData = { windowId: messageFrameData.windowId };
- windowData.frames.push(frameData);
- }
- if (!frameData.processed) {
- frameData.content = messageFrameData.content;
- frameData.baseURI = messageFrameData.baseURI;
- frameData.title = messageFrameData.title;
- frameData.url = messageFrameData.url;
- frameData.canvases = messageFrameData.canvases;
- frameData.fonts = messageFrameData.fonts;
- frameData.stylesheets = messageFrameData.stylesheets;
- frameData.images = messageFrameData.images;
- frameData.posters = messageFrameData.posters;
- frameData.videos = messageFrameData.videos;
- frameData.usedFonts = messageFrameData.usedFonts;
- frameData.shadowRoots = messageFrameData.shadowRoots;
- frameData.processed = messageFrameData.processed;
- frameData.scrollPosition = messageFrameData.scrollPosition;
- frameData.scrolling = messageFrameData.scrolling;
- frameData.adoptedStyleSheets = messageFrameData.adoptedStyleSheets;
- }
- });
- const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
- if (!remainingFrames) {
- windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
- if (windowData.resolve) {
- if (windowData.requestedFrameId) {
- windowData.frames.forEach(frameData => {
- if (frameData.windowId == windowData.requestedFrameId) {
- frameData.requestedFrame = true;
- }
- });
- }
- windowData.resolve(windowData.frames);
- }
- }
- }
- }
- function processFrames(doc, options, parentWindowId, sessionId) {
- const frameElements = getFrames(doc);
- processFramesAsync(doc, frameElements, options, parentWindowId, sessionId);
- if (frameElements.length) {
- processFramesSync(doc, frameElements, options, parentWindowId, sessionId);
- }
- }
- function processFramesAsync(doc, frameElements, options, parentWindowId, sessionId) {
- const frames = [];
- let requestTimeouts;
- if (sessions.get(sessionId)) {
- requestTimeouts = sessions.get(sessionId).requestTimeouts;
- } else {
- requestTimeouts = {};
- sessions.set(sessionId, { requestTimeouts });
- }
- frameElements.forEach((frameElement, frameIndex) => {
- const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
- frameElement.setAttribute(helper.WIN_ID_ATTRIBUTE_NAME, windowId);
- frames.push({ windowId });
- });
- sendInitResponse({ frames, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
- frameElements.forEach((frameElement, frameIndex) => {
- const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
- try {
- sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options, scrolling: frameElement.scrolling });
- } catch (error) {
- // ignored
- }
- requestTimeouts[windowId] = globalThis.setTimeout(() => sendInitResponse({ frames: [{ windowId, processed: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
- });
- delete doc.documentElement.dataset.requestedFrameId;
- }
- function processFramesSync(doc, frameElements, options, parentWindowId, sessionId) {
- const frames = [];
- frameElements.forEach((frameElement, frameIndex) => {
- const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
- let frameDoc;
- try {
- frameDoc = frameElement.contentDocument;
- } catch (error) {
- // ignored
- }
- if (frameDoc) {
- try {
- const frameWindow = frameElement.contentWindow;
- frameWindow.stop();
- clearFrameTimeout("requestTimeouts", sessionId, windowId);
- processFrames(frameDoc, options, windowId, sessionId);
- frames.push(getFrameData(frameDoc, frameWindow, windowId, options, frameElement.scrolling));
- } catch (error) {
- frames.push({ windowId, processed: true });
- }
- }
- });
- sendInitResponse({ frames, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
- delete doc.documentElement.dataset.requestedFrameId;
- }
- function clearFrameTimeout(type, sessionId, windowId) {
- const session = sessions.get(sessionId);
- if (session && session[type]) {
- const timeout = session[type][windowId];
- if (timeout) {
- globalThis.clearTimeout(timeout);
- delete session[type][windowId];
- }
- }
- }
- function createFrameResponseTimeout(sessionId, windowId) {
- const session = sessions.get(sessionId);
- if (session && session.responseTimeouts) {
- session.responseTimeouts[windowId] = globalThis.setTimeout(() => sendInitResponse({ frames: [{ windowId: windowId, processed: true }], sessionId: sessionId }), TIMEOUT_INIT_RESPONSE_MESSAGE);
- }
- }
- function cleanupFrames(frameElements, parentWindowId, sessionId) {
- frameElements.forEach((frameElement, frameIndex) => {
- const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
- frameElement.removeAttribute(helper.WIN_ID_ATTRIBUTE_NAME);
- try {
- sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId });
- } catch (error) {
- // ignored
- }
- });
- frameElements.forEach((frameElement, frameIndex) => {
- const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
- let frameDoc;
- try {
- frameDoc = frameElement.contentDocument;
- } catch (error) {
- // ignored
- }
- if (frameDoc) {
- try {
- cleanupFrames(getFrames(frameDoc), windowId, sessionId);
- } catch (error) {
- // ignored
- }
- }
- });
- }
- function sendInitResponse(message) {
- message.method = INIT_RESPONSE_MESSAGE;
- try {
- top.singlefile.processors.frameTree.initResponse(message);
- } catch (error) {
- sendMessage(top, message, true);
- }
- }
- function sendMessage(targetWindow, message, useChannel) {
- if (targetWindow == top && browser && browser.runtime && browser.runtime.sendMessage) {
- browser.runtime.sendMessage(message);
- } else {
- if (useChannel) {
- const channel = new MessageChannel();
- targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method, sessionId: message.sessionId }), TARGET_ORIGIN, [channel.port2]);
- channel.port1.postMessage(message);
- } else {
- targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
- }
- }
- }
- function getFrameData(document, globalThis, windowId, options, scrolling) {
- const docData = helper.preProcessDoc(document, globalThis, options);
- const content = helper.serialize(document);
- helper.postProcessDoc(document, docData.markedElements, docData.invalidElements);
- const baseURI = document.baseURI.split("#")[0];
- return {
- windowId,
- content,
- baseURI,
- url: document.location.href,
- title: document.title,
- canvases: docData.canvases,
- fonts: docData.fonts,
- stylesheets: docData.stylesheets,
- images: docData.images,
- posters: docData.posters,
- videos: docData.videos,
- usedFonts: docData.usedFonts,
- shadowRoots: docData.shadowRoots,
- scrollPosition: docData.scrollPosition,
- scrolling,
- adoptedStyleSheets: docData.adoptedStyleSheets,
- processed: true
- };
- }
- function getFrames(document) {
- let frames = Array.from(document.querySelectorAll(FRAMES_CSS_SELECTOR));
- document.querySelectorAll(ALL_ELEMENTS_CSS_SELECTOR).forEach(element => {
- const shadowRoot = helper.getShadowRoot(element);
- if (shadowRoot) {
- frames = frames.concat(...shadowRoot.querySelectorAll(FRAMES_CSS_SELECTOR));
- }
- });
- return frames;
- }
- exports.TIMEOUT_INIT_REQUEST_MESSAGE = TIMEOUT_INIT_REQUEST_MESSAGE;
- exports.cleanup = cleanup;
- exports.getAsync = getAsync;
- exports.getSync = getSync;
- exports.initResponse = initResponse;
- Object.defineProperty(exports, '__esModule', { value: true });
- }));
|