(function () {
    const originalSend = XMLHttpRequest.prototype.send;
    const originalOpen = XMLHttpRequest.prototype.open;

    XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
        this._url = url;   // 保存请求 URL 以便后续使用
        this._method = method;
        this._async = async;
        originalOpen.apply(this, arguments);  // 保持原来的 open 方法
    };

    XMLHttpRequest.prototype.send = function (body) {
        const xhr = this;  // 保存当前 XMLHttpRequest 对象的引用

        console.log('拦截到 XHR 请求的响应:', xhr.responseText);
        // 拦截 onreadystatechange,获取响应数据
        xhr.addEventListener('readystatechange', function () {
            if (xhr.readyState === 4) {  // readyState 4 表示请求已完成
                console.log('拦截到 XHR 请求的响应:', xhr.responseText);

                // 在这里你可以对响应数据进行处理
                // alert(xhr.responseText)
                //拦截指定的url
                if (xhr._url.includes('keyword')) {
                    console.log(JSON.parse(xhr.responseText).data)
                }
            }
        });

        // 调用原始 send 方法
        originalSend.apply(this, arguments);
    };
})();

标签: js, chrome, xhr, 拦截请求

添加新评论