【问题标题】:How to keep the function in chrome console and run it after reloading the page?如何在 chrome 控制台中保留该功能并在重新加载页面后运行它?
【发布时间】:2018-07-02 22:46:52
【问题描述】:

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

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

【问题讨论】:

  • 一种方法是将其放入 Tampermonkey 用户脚本中
  • 或者使用XMLHttpRequestDOMParser 并且根本不重新加载页面。
  • 如果您重新加载页面,setInterval 将不再像看起来那样工作。
  • 具体怎么做?

标签: javascript google-chrome-devtools google-chrome-console


【解决方案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有参数,你应该发送那些as a form

【讨论】:

    【解决方案2】:

    根据您的代码,您正在等待一个异步函数,该函数将创建一个具有“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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多