李恒道 发表于 2021-7-19 16:44:15

[油猴脚本开发指南]XHR劫持代码原理解释

代码可以参考https://bbs.tampermonkey.net.cn/forum.php?mod=viewthread&tid=357&highlight=xmlhttp

这是我之前在国外论坛找到的一个小栗子

```

function addXMLRequestCallback(callback){
    是一个劫持的函数
    var oldSend, i;
    if( XMLHttpRequest.callbacks ) {
      判断XMLHttpRequest对象下是否存在回调列表,存在就push一个回调的函数
      // we've already overridden send() so just add the callback
      XMLHttpRequest.callbacks.push( callback );
    } else {
      // create a callback queue
      XMLHttpRequest.callbacks = ;
      如果不存在则在xmlhttprequest函数下创建一个回调列表
      // store the native send()
      oldSend = XMLHttpRequest.prototype.send;
      获取旧xml的send函数,并对其进行劫持
      // override the native send()
      XMLHttpRequest.prototype.send = function(){
            // process the callback queue
            // the xhr instance is passed into each callback but seems pretty useless
            // you can't tell what its destination is or call abort() without an error
            // so only really good for logging that a request has happened
            // I could be wrong, I hope so...
            // EDIT: I suppose you could override the onreadystatechange handler though
            for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
                XMLHttpRequest.callbacks( this );
            }
            循环回调xml内的回调函数
            // call the native send()
            oldSend.apply(this, arguments);
         由于我们获取了send函数的引用,并且复写了send函数,这样我们在调用原send的函数的时候,需要对其传入引用,而arguments是传入的参数
      }
    }
}

// e.g.
addXMLRequestCallback( function( xhr ) {
      调用劫持函数,填入一个function的回调函数
      回调函数监听了对xhr调用了监听load状态,并且在触发的时候再次调用一个function,进行一些数据的劫持以及修改
      xhr.addEventListener("load", function(){
      if ( xhr.readyState == 4 && xhr.status == 200 ) {
            console.log( xhr.responseURL );
      }
    });

});
```

806350554 发表于 2022-2-18 12:49:18

真神了

popcc 发表于 2022-8-26 11:59:31

牛皮,学到了

Major 发表于 2022-10-29 10:18:52

怎样拦截和 补货特定网址的 xhr

李恒道 发表于 2022-10-29 14:28:58

Major 发表于 2022-10-29 10:18
怎样拦截和 补货特定网址的 xhr

直接在send 里做判断就好了

Major 发表于 2022-11-8 11:09:02

可以将劫持的内容修改再返回到网页吗,或者劫持修改post内容再提交

李恒道 发表于 2022-11-8 11:11:45

Major 发表于 2022-11-8 11:09
可以将劫持的内容修改再返回到网页吗,或者劫持修改post内容再提交
可以的
但返回内容修改要参考拦截器那节

Major 发表于 2022-11-12 12:12:37

李恒道 发表于 2022-11-8 11:11
可以的
但返回内容修改要参考拦截器那节

可以发下链接吗

李恒道 发表于 2022-11-12 14:57:39

Major 发表于 2022-11-12 12:12
可以发下链接吗

[油猴脚本开发指南]XHR劫持的第二种格式
https://bbs.tampermonkey.net.cn/thread-1201-1-1.html

呀嘻耶耶 发表于 2023-5-12 13:01:22

哥哥牛逼,超级好用
页: [1]
查看完整版本: [油猴脚本开发指南]XHR劫持代码原理解释