fetchElements

Convert fetch body to dom elements.

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/425782/926860/fetchElements.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name          fetchElements
// @namespace     https://greasyfork.org
// @version       0.1
// @description   Convert fetch body to dom elements.
// @match         *://*/*
// @grant         none
// ==/UserScript==

/**
 * fix Fetch Chinese garbled
 * https://segmentfault.com/q/1010000004338890
 * https://blog.shovonhasan.com/using-promises-with-filereader/
 * @param {Binary} https://developer.mozilla.org/docs/Web/API/FileReader/readAsText
 * @return {String}
 */
const binary2Text = async (input) => {
  let reader = new FileReader();
  return new Promise((resolve, reject) => {
    reader.onerror = () => {
      reader.abort();
      reject(new DOMException('Problem parsing input.'));
    };
    reader.onload = () => {
      resolve(reader.result);
    };
    reader.readAsText(input);
  });
};

/**
 * https://stackoverflow.com/a/35385518
 * @param {String} HTML representing any number of sibling elements
 * @return {NodeList}
 */
const htmlToElements = (htmlSrc) => {
  let template = document.createElement('template');
  template.innerHTML = htmlSrc;
  return template.content;
};

/**
 * @param {String} fetchUrl
 * @param {Object} fetchOptions
 * @return {NodeList}
 */
const fetchElements = async (fetchUrl, fetchOptions = {}) => {
  const body_response = await fetch(fetchUrl, fetchOptions);
  const body_blob = await body_response.blob();
  const body_utf8Text = await binary2Text(body_blob);
  const body_elements = htmlToElements(body_utf8Text);
  return body_elements;
};