爬虫 破解 定时刷新 js 取消全局 setTimeout setInterval 方法

1,358 阅读2分钟

----欢迎查看我的博客----

取消setTimeout setInterval

  写过爬虫的哥们或者做过一些黑客的朋友们都知道,有时候我们可能想通过 js 脚本注入,完成对页面的逻辑 dom 节点的爬取或者操作, 经常可以看到 ,对方的反爬措施, setTimeout 执行一些代码逻辑 ,而且都是编译工具 闭包去编译, 导致无法进行 js 脚本注入的 操作,这里我列举几种 方式。

方法一

// Set a fake timeout to get the highest timeout id
var highestTimeoutId = setTimeout(";");
for (var i = 0 ; i < highestTimeoutId ; i++) {
    clearTimeout(i); 
}

  这段代码开始我没有搞懂这是为什么?分号其实不重要,直到我写了一个demo才明白是这个意思。我们来看代码:

<!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>

可以看出。这个id是递增的。那么取消全部,意思是找一个最大值,然后将小于它的全部取消就可以了。所以第一种方式的原理就是这样。

方法二

思路大概是重写 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 的小技巧。好奇的朋友们多试试吧