取消setTimeout setInterval
??寫過(guò)爬蟲(chóng)的哥們或者做過(guò)一些黑客的朋友們都知道,有時(shí)候我們可能想通過(guò) js 腳本注入耀找,完成對(duì)頁(yè)面的邏輯 dom 節(jié)點(diǎn)的爬取或者操作椭微, 經(jīng)承锼危可以看到 疤孕,對(duì)方的反爬措施传蹈, setTimeout 執(zhí)行一些代碼邏輯 厚脉,而且都是編譯工具 閉包去編譯习寸, 導(dǎo)致無(wú)法進(jìn)行 js 腳本注入的 操作,這里我列舉幾種 方式傻工。
方法一
// Set a fake timeout to get the highest timeout id
var highestTimeoutId = setTimeout(";");
for (var i = 0 ; i < highestTimeoutId ; i++) {
clearTimeout(i);
}
??這段代碼開(kāi)始我沒(méi)有搞懂這是為什么霞溪?分號(hào)其實(shí)不重要,直到我寫了一個(gè)demo才明白是這個(gè)意思精钮。我們來(lái)看代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
const highestTimeoutId = setTimeout(() => {});
const highestTimeoutId2 = setTimeout(() => {});
const highestTimeoutId3 = setTimeout(() => {});
console.log(`id1:${highestTimeoutId}`, `id2:${highestTimeoutId2}`, `id3:${highestTimeoutId3}`); //2,3,4
</script>
</body>
</html>
可以看出威鹿。這個(gè)id是遞增的。那么取消全部轨香,意思是找一個(gè)最大值忽你,然后將小于它的全部取消就可以了。所以第一種方式的原理就是這樣臂容。
方法二
思路大概是重寫 setTimeout setInterval 科雳。
window.timeoutList = new Array();
window.intervalList = new Array();
window.oldSetTimeout = window.setTimeout;
window.oldSetInterval = window.setInterval;
window.oldClearTimeout = window.clearTimeout;
window.oldClearInterval = window.clearInterval;
window.setTimeout = function(code, delay) {
var retval = window.oldSetTimeout(code, delay);
window.timeoutList.push(retval);
return retval;
};
window.clearTimeout = function(id) {
var ind = window.timeoutList.indexOf(id);
if(ind >= 0) {
window.timeoutList.splice(ind, 1);
}
var retval = window.oldClearTimeout(id);
return retval;
};
window.setInterval = function(code, delay) {
var retval = window.oldSetInterval(code, delay);
window.intervalList.push(retval);
return retval;
};
window.clearInterval = function(id) {
var ind = window.intervalList.indexOf(id);
if(ind >= 0) {
window.intervalList.splice(ind, 1);
}
var retval = window.oldClearInterval(id);
return retval;
};
window.clearAllTimeouts = function() {
for(var i in window.timeoutList) {
window.oldClearTimeout(window.timeoutList[i]);
}
window.timeoutList = new Array();
};
window.clearAllIntervals = function() {
for(var i in window.intervalList) {
window.oldClearInterval(window.intervalList[i]);
}
window.intervalList = new Array();
};
setInterval('console.log(\'a\')', 1000);
setInterval('console.log(\'b\')', 500);
setInterval('console.log(\'c\')', 750);
setTimeout('clearAllIntervals()', 10000);
這篇比較短,主要記錄一下 hacker 的小技巧脓杉。好奇的朋友們多試試吧