匿名 window.setTimeout 函数重新加载页面

anonymous window.setTimeout function reloading page

使用 Tampermonkey 改变网站的行为。使用以下代码的网站有一些问题:

<script language="JavaScript">
        if (typeof jQuery != 'undefined') {
            jQuery(window).load(function() {
                 window.setTimeout(function() {
                     window.location.replace(window.location.href);
                 }, 180E3);
             });
         }
</script>

如何 remove/prevent 它重新加载页面?

在不与 jQuery 混淆的情况下,如果您的脚本在那段代码之前运行,您可以执行以下操作:

jQuery.fn.load = function() {
  console.log("Tried to reload the page!")
}

// Then the following, outputs 'Tried to reload the page!' and does nothing else
jQuery(window).load(function() {
  // code
})

如果之后您仍然需要 load 功能,您 可以 执行以下操作:

var oldLoad = jQuery.fn.load
var undesiredCallback = "function() {
             window.setTimeout(function() {
                 window.location.replace(window.location.href);
             }, 180E3);
         }"
jQuery.fn.load = function(callback) {
  if(callback.toString() !== undesiredCallback) {
    oldLoad(callback);
  }
}

但它依赖于浏览器并且非常不可靠

另一种方法是添加 onbeforeunload 事件,但这会在您的选项卡上弹出提示:

window.onbeforeunload = function() {
    return "Stay here please";
}

您还可以覆盖 setTimeout 功能。

var oldSetTimeout = window.setTimeout;
window.setTimeout = function(func,interval){ 
    if(typeof func === "function" && func.toString().indexOf('window.location.replace(window.location.href)') > -1){
        /*do nothing*/
    }else{ 
        oldSetTimeout(func,interval) 
    } 
}