porxy 代理在爬虫方面和HOOK,的功能差不多,都是监控对象属性
1. 单对象代理
document = new Proxy(document,{
get(target,p,receiver){
let res = Reflect.get(target,p,receiver)
console.log(`对象document,调用属性/方法: ${p},
属性/方法类型: ${typeof p} ,值: ${res},值类型: ${typeof res}`)
return res
},
set(target, p, value, receiver) {
console.log(`对象document,设置属性/方法: ${p},
属性/方法类型: ${typeof p} ,值:${value},值类型: ${typeof target[p]}`)
return Reflect.set(target,p,value,receiver)
}
})
document.referrer = 'https://www.jianshu.com/'
console.log(document.referrer)
2. 对象以数组方式加入代理
function SetProxy(proxyObjs) {
for (let i = 0; i < proxyObjs.length; i++) {
const handler = `{
get: function(target, property, receiver) {
console.log("方法:", "get ", "对象:", "${proxyObjs[i]}", " 属性:", property, " 属性类型:", typeof property, ", 属性值:", target[property]);
return target[property];
},
set: function(target, property, value, receiver) {
console.log("方法:", "set ", "对象:", "${proxyObjs[i]}", " 属性:", property, " 属性类型:", typeof property, ", 属性值:", value, ", 属性值类型:", typeof target[property]);
return Reflect.set(...arguments);
}
}`;
eval(`try {
${proxyObjs[i]};
${proxyObjs[i]} = new Proxy(${proxyObjs[i]}, ${handler});
} catch (e) {
${proxyObjs[i]} = {};
${proxyObjs[i]} = new Proxy(${proxyObjs[i]}, ${handler});
}`);
}
}
/*
传入需要代理的对象:
window,localStorage,document,navigator,screen,location,sessionStorage
这里对象很多,需要根据实际情况来补,以下是常用的补环境
*/
SetProxy(
["window","localStorage","document","navigator","screen","location","sessionStorage"]
)
当使用proxy 代理之后,所有经过属性方法取值设值都会被监控到,这在爬虫补环境中非常有用