GM_fetch

fetch pollyfill using GM_xmlhttpRequest

目前为 2021-02-07 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/421384/898562/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)
	})
}

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址