from–https://blog.dqv5.com/2021/04/04/tampermonkey-request-intercept/
油猴插件简介
Tampermonkey(油猴)是最受欢迎的浏览器扩展之一,拥有超过1000万用户。
Tampermonkey用于在网站上运行所谓的用户脚本(有时也称为Greasemonkey脚本)。
用户脚本是小型计算机程序,可以更改页面的布局,添加或删除新功能和内容或自动执行操作
安装插件
编写脚本
启用运行
拦截ajax请求
直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | // ==UserScript==
// @name 百度搜索测试
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 代码功能:百度搜索123,返回456的搜索结果
// @author You
// @match https://www.baidu.com/*
// @grant none
// ==/UserScript==
(function () {
console.log('加载脚本');
/**
* 拦截并修改ajax请求
*/
window.beforeXMLHttpRequestOpen = function (xhr, options) {
console.log('before open', xhr);
// 修改url
options.url = options.url.replace('wd=123', 'wd=456');
// 修改method
// options.method = 'POST';
};
/**
* 拦截并修改ajax请求
*/
window.beforeXMLHttpRequestSend = function (xhr, body) {
console.log('before send', xhr);
// 修改请求头
xhr.setRequestHeader('key1', 'value1');
};
/**
* 重写open方法
* https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/open
*/
XMLHttpRequest.prototype.myOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
// 用对象便于修改参数
var options = {
method: method,
url: url,
async: async,
user: user,
password: password
};
if ('function' === typeof window.beforeXMLHttpRequestOpen) {
window.beforeXMLHttpRequestOpen(this, options);
}
this.myOpen(options.method, options.url, options.async);
};
/**
* 重写send方法
* https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/send
*/
XMLHttpRequest.prototype.mySend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (body) {
if ('function' === typeof window.beforeXMLHttpRequestSend) {
window.beforeXMLHttpRequestSend(this, body);
}
this.mySend(body);
};
})(); |