Przeglądaj źródła

use utf-8 charset as fallback on errors when decoding text

Gildas 7 lat temu
rodzic
commit
e3839dc337
1 zmienionych plików z 18 dodań i 10 usunięć
  1. 18 10
      lib/single-file/single-file-browser.js

+ 18 - 10
lib/single-file/single-file-browser.js

@@ -111,24 +111,32 @@ this.SingleFile = this.SingleFile || (() => {
 				if (!charSet) {
 					charSet = "utf-8";
 				}
+				const arrayBuffer = await resourceContent.arrayBuffer();
+				if (DEBUG) {
+					log("  // ENDED   download url =", resourceURL, "delay =", Date.now() - startTime);
+				}
 				try {
-					const arrayBuffer = await resourceContent.arrayBuffer();
-					if (DEBUG) {
-						log("  // ENDED   download url =", resourceURL, "delay =", Date.now() - startTime);
-					}
-					const textContent = (new TextDecoder(charSet)).decode(arrayBuffer);
-					if (options.maxResourceSizeEnabled && textContent.length > options.maxResourceSize * ONE_MB) {
+					return getTextContent(charSet, arrayBuffer, options);
+				} catch (error) {
+					try {
+						return getTextContent("utf-8", arrayBuffer, options);
+					} catch (error) {
 						return "";
-					} else {
-						return textContent;
 					}
-				} catch (error) {
-					return "";
 				}
 			}
 		}
 	}
 
+	function getTextContent(charSet, arrayBuffer, options) {
+		const textContent = (new TextDecoder(charSet)).decode(arrayBuffer);
+		if (options.maxResourceSizeEnabled && textContent.length > options.maxResourceSize * ONE_MB) {
+			return "";
+		} else {
+			return textContent;
+		}
+	}
+
 	const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
 	const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;