js fetch hook

// ==UserScript==
// @name         Hook fetch
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!

// @include      *
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';
    window.au_fetch=window.fetch;
    window.fetch=function(url){
        console.log(url);
        return window.au_fetch.apply(window,arguments).then((response) => {
            const reader = response.body.getReader();
            const stream = new ReadableStream({
                start(controller) {
                    function push() {
                        // "done"是一个布尔型,"value"是一个Unit8Array
                        reader.read().then((e) => {
                            let { done, value }=e;
                            // 判断是否还有可读的数据?
                            console.log(done,new TextDecoder("utf-8").decode(value));
                            if (done) {
                                // 告诉浏览器已经结束数据发送
                                controller.close();
                                return;
                            }
                            // 取得数据并将它通过controller发送给浏览器
                            controller.enqueue(value);
                            push();
                        });
                    }
                    push();
                }
            });
            let ret=new Response(stream, { headers: { "Content-Type": "text/html" } })
            console.log(stream,ret);
            return ret;
        });
    };
    // Your code here...
})();

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容