[英]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();
笔记:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.