4

I have a code that i want to put in chrome console

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);
}

The function above gets some data from the website, but if it didn't find the data i want it to reload every minute until the data is available.
I want to insert the code only once and leave the browser working.
So how to run the function every time i reload the page ?

nadhirxz
  • 171
  • 2
  • 15

2 Answers2

3

You can change your code to not reload the page every time but instead request it via XMLHttpRequest. You can then parse the response into a document using 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();

Notes:

  1. First make sure you're currently on that page so you won't get CORS error.
  2. If the url has parameters, you should send those as a form.
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

As per your code, you are waiting for an async function that will create an element with a "dispo" classname. Then when it is loaded, you're gonna do something. If it isn't, you will check it in 1 minute.

Try below code

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();
Liang
  • 507
  • 2
  • 9