[英]Javascript delay after click on element to wait for next page to load
我正在为我的应用程序创建一个测试过程,我希望代码中的操作具有同步延迟,以便等待下一页加载,然后搜索所需的选择器。 我用过setTimeout,但是返回在那儿不起作用。
var myelement = "click button here";
if (myelement.indexOf("click")>=0) {
for (var i=1; i<=4 ; i++) {
title = document.querySelector("#element > .row:nth-of-type("+i+") > .title").textContent;
if ( title == "title x" ) {
document.querySelector("#element > .row:nth-of-type("+i+") > .button > a").click();
//wait for 5sec to load next page
var content = document.querySelector("#message").textContent.trim();
if (content == "my content" ) {
return true;
}
}
}
}
如果我不插入延迟,则第9行(可变内容)返回错误TypeError: Cannot read property 'textContent' of null
这里有什么帮助吗? 谢谢
网页没有服务器和数据库,Cookie或localStorage时没有任何状态,因此,如果您尝试执行setTimout并重新加载页面,则您将丢失状态,并且该功能将不会触发。
您需要使用诸如localStorage之类的内容来保存页面加载之间的状态。 检查状态值,并在页面加载时采取适当的措施。
var myelement = "click button here";
// this will be run on page load
// if the localStorage.content is set you have passed from the previous page
if (localStorage.content) {
// check the value
if (content == "my content") {
console.log(localStorage.content, true)
// reset the localStorage value
localStorage.removeItem('content')
}
}
if (myelement.indexOf("click") >= 0) {
for (var i = 1; i <= 4; i++)(function(i) {
title = document.querySelector("#element > .row:nth-of-type(" + i + ") > .title").textContent;
if (title == "title x") {
document.querySelector("#element > .row:nth-of-type(" + i + ") > .button > a").click();
// set the localStorage value for the next page load
localStorage.content = document.querySelector("#message").textContent.trim();
window.location.href = '/somewhere-else'
}
})(i)
}
不要使用setTimeout ,它在循环中不能很好地工作。 因此,请使用以下实现的睡眠
function sleep(mills){
var t=new Date().getTime(); // Store current Time;
while((new Date().getTime()-t)<mills);
}
因此,可以循环使用您刚刚为您创建的sleep
功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.