javascript - 覆盖 XMLHttpRequest.responseText

标签 javascript

我会尽力解释我的问题,但说实话,我自己也有点困惑,所以我无法想象这对你们来说会容易得多。

对,我正在为我经常访问的网站的用户脚本创建一个脚本。我想做的是劫持任何ajax请求,我做得很好,然后修改responseText。

我似乎无法写入responseText,我可以很好地阅读它并且它显示了很好的响应,但无论我尝试什么,我都无法更改它的值。

我在控制台中没有收到任何错误,我在代码中留下了注释以显示记录的内容。

我本来打算废弃它,但了解我,我错过了一些愚蠢而明显的东西,只是看不到它。

提前致谢。

(function(send) { 
    XMLHttpRequest.prototype.send = function(data) { 
        this.addEventListener('readystatechange', function() { 
            if(typeof data == 'string'){
                if(data.indexOf('room.details_1') > -1){
                    if(this.readyState == 4 && this.status == 200){
                        console.log('Before: ' + JSON.parse(this.responseText).body.user.profile.username); // Shows NameNumber1
                        var temp = JSON.parse(this.responseText);
                        temp.body.user.profile.username = 'NameNumber2';
                        this.responseText = JSON.stringify(temp);
                        console.log('Temp: ' + temp.body.user.profile.username); // Shows NameNumber2
                        console.log('After: ' + JSON.parse(this.responseText).body.user.profile.username); // Shows NameNumber1 <-- This is the problem.
                        console.log(this); // Shows the XMLHttpRequest object, with the original responseText rather than the modified one.
                    }
                }
            }
        }, false);
        send.call(this, data);
    }; 
})(XMLHttpRequest.prototype.send);

最佳答案

我知道这已经晚了 3 年,但我已将其包含在此处,以供遇到此线程的其他人使用。我以前做过这个...这是直接从我的脚本复制并粘贴的内容。您应该能够将responseText更改为可写。

Object.defineProperty(this, "responseText", {writable: true});
this.responseText = '{"success":true}';

关于javascript - 覆盖 XMLHttpRequest.responseText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23901337/

相关文章:

javascript - 是否需要在链接页面中指定 javascript 和 ccs 引用?

javascript - 如何检测 Angular 2 中的 URL 变化?

JavaScript 字符串替换问题

javascript - 如果我开始使用 React/flux,是否应该从头开始重新创建所有页面(html 和 css)?

javascript - AngularJS 中如何将数据从一个异步函数传递到另一个异步函数

javascript - Angular 2 Kendo UI 上的日期时间过滤器

javascript - 在目标页面完成加载之前添加样式元素

javascript - 使用 JavaScript Onclick 事件将数据传递到 Django 中的views.py?

javascript - 如何使用闭包概念获得相同的输出

javascript - 具有动态长度的 Angular 中的 Bootstrap Accordion