2

我有一个要放入 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);
}

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

4

2 回答 2

1

根据您的代码,您正在等待一个异步函数,该函数将创建一个具有“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();
于 2018-07-02T23:22:01.840 回答
1

您可以更改代码以不每次都重新加载页面,而是通过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 有参数,您应该将它们作为 form发送。
于 2018-07-02T23:27:36.207 回答