Greasy Fork

Greasy Fork is available in English.

GM_fetch

fetch pollyfill using GM_xmlhttpRequest

当前为 2021-02-07 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.greasyfork.icu/scripts/421384/898554/GM_fetch.js

function GM_fetch(url, opt){
	function blobTo(to, blob) {
		if (to == "arrayBuffer" && blob.arrayBuffer) return blob.arrayBuffer()
		return new Promise((resolve, reject) => {
			var fileReader = new FileReader()
			fileReader.onload = function (event) { if (to == "base64") resolve(event.target.result); else resolve(event.target.result) }
			if (to == "arrayBuffer") fileReader.readAsArrayBuffer(blob)
			else if (to == "base64") fileReader.readAsDataURL(blob) // "data:*/*;base64,......"
			else if (to == "text") fileReader.readAsText(blob, "utf-8")
			else reject("unknown to")
		})
	}
	return new Promise((resolve, reject)=>{
		// https://www.tampermonkey.net/documentation.php?ext=dhdg#GM_xmlhttpRequest
		opt = opt || {}
		opt.url = url
		opt.data = opt.body
		opt.responseType = "blob"
		opt.onload = (resp)=>{
			var blob = resp.response
			resp.blob = ()=>Promise.resolve(blob)
			resp.arrayBuffer = ()=>blobTo("arrayBuffer", blob)
			resp.text = ()=>blobTo("text", blob)
			resp.json = async ()=>JSON.parse(await blobTo("text", blob))
			resolve(resp)
		}
		opt.ontimeout = ()=>reject("fetch timeout")
		opt.onerror   = ()=>reject("fetch error")
		opt.onabort   = ()=>reject("fetch abort")
		GM_xmlhttpRequest(opt)
	})
}