想要重写 setTimeout 方法,发现有动态引入的js,需要改成自己的js,以下教教大家这个需求。
一、重新定义setTimeout方法
直接上代码和注释:
//定义 _setTimeout 接收 setTimeout
var _setTimeout = window.setTimeout;
// 重写setTimeout
window.setTimeout = function(ref, tm){
code = '' + ref;//把方法tostring
//判断内容有包含这个链接,可以直接方法
if(code.indexOf('www.jsjiami.com/main.js') !== -1){
ref = function () {
//我把它改成想改成其他的js
var script = document.createElement("script");
script.setAttribute("src","https://www.baidu.com/main.js");
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(script, s);
console.log('被劫持了哦1');
}
}
//判断内容有包含这个方法
if(code.indexOf('method') !== -1){
ref = function () {
console.log('被劫持了哦2');
return ;
}
}
var argu = Array.prototype.slice.call(arguments,2);
var f = function(){
ref.apply(null, argu);
};
return _setTimeout(f, tm);
}
应该看得明白吧,配合注释看。
比如的代码。
setTimeout(function () {
//比如我要劫持这个引入js
var script = document.createElement("script");
script.setAttribute("src","https://www.jsjiami.com/main.js");
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(script, s);
},100);
直接请求百度了。
方法劫持我就不演示了。