如何在 chrome 控制台中保留该功能并在重新加载页面后 运行 它?

How to keep the function in chrome console and run it after reloading the page?

我有一个代码想放入 chrome 控制台

var a = document.getElementsByClassName("dispo");
if (a.length > 0) {
    for (let i = 0; i < a.length ; i++) {
        if (a[i].textContent.length > 0) {
           console.log(a[i].parentElement.textContent.substr(0,10) + " - " + a[i].textContent);   
        }
    } 
} else {
    setInterval(function(){ document.location.reload() },60000);
}

上面的函数从网站获取一些数据,但如果它没有找到数据,我希望它每分钟重新加载一次,直到数据可用。
我只想插入一次代码,让浏览器继续工作。
那么如何在每次重新加载页面时 运行 该函数?

根据您的代码,您正在等待一个异步函数,该函数将创建一个具有 "dispo" 类名的元素。然后当它被加载时,你会做一些事情。如果不是,您将在 1 分钟内检查它。

试试下面的代码

const checkDispo=()=>{
    var a = document.getElementsByClassName("dispo");
    if (a.length > 0) {
        clearInterval(intv);
        for (let i = 0; i < a.length ; i++) {
            if (a[i].textContent.length > 0) {
               console.log(a[i].parentElement.textContent.substr(0,10) + " - " + a[i].textContent);   
            }
        } 
    }
}

const intv=setInterval(checkDispo,60000);
checkDispo();

您可以将代码更改为不每次都重新加载页面,而是通过 XMLHttpRequest 请求。然后,您可以使用 DOMParser:

将响应解析为文档
function request(callback) {                            // request will request the page content as text (without reloading)
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://your-url-here");
    xhr.onload = function() {
        callback(xhr.response);
    };
    xhr.send();
}

function next() {                                       // next will be called each time instead of reloading
    request(function(response) {                        // first we request the page
        var doc = new DOMParser().parseFromString(response, "text/html"); // then we parse it as a document

        var a = doc.getElementsByClassName("dispo");    // use doc instead of document (doc will be the newly requested document/page)
        if (a.length > 0) {
            for (let i = 0; i < a.length ; i++) {
                if (a[i].textContent.length > 0) {
                    console.log(a[i].parentElement.textContent.substr(0,10) + " - " + a[i].textContent);   
                }
            } 
        } else {
            setTimeout(next, 60000);                    // if we didn't find anything, then call next after a minute
        }
    });
}

next();

备注:

  1. 首先确保您当前在该页面上,这样您就不会收到 CORS 错误。
  2. 如果 url 有参数,你应该发送那些 as a form.