最近需要在一个脚本中加入拦截b站直播流的功能,但并没有找到相关文章或者脚本,所以写篇文章分享一下捣鼓出来的成果。
首先在脚本头部加入
// @run-at document-start
// @grant unsafeWindow
把运行时间设置为document-start,确保能拦截到较早发出的请求。
const originFetch = fetch;
unsafeWindow.fetch = (...arg) => {
console.log('fetch arg', ...arg);
if (arg[0].indexOf('bilivideo.com') > -1) {
//console.log('拦截直播流')
return new Promise(() => {
throw new Error();
});
} else {
//console.log('通过')
return originFetch(...arg);
}
}
这里我通过url判断是否为获取b站直播流的请求,如果不是则不拦截,避免误伤。