【问题标题】:Javascript delay after click on element to wait for next page to load单击元素以等待下一页加载后的Javascript延迟
【发布时间】:2018-02-07 12:51:17
【问题描述】:

我正在为我的应用程序创建一个测试过程,我希望在我的代码中同步延迟一个操作,以便等待下一页加载,然后搜索我需要的选择器。 我已经使用了 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 行(var content)会返回错误TypeError: Cannot read property 'textContent' of null

这里有什么帮助吗? 谢谢

【问题讨论】:

  • 如果您尝试同步暂停操作,您的做法是错误的。也就是说,超时不是同步的,它们是异步的。而且你不能从异步回调中返回——这在术语上是矛盾的。查看promises

标签: javascript automated-tests settimeout delay synchronous


【解决方案1】:

如果没有服务器和数据库、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)
}

【讨论】:

    【解决方案2】:

    不要使用 setTimeout,它在循环中效果不佳。所以,使用 sleep 实现如下

    function sleep(mills){
        var t=new Date().getTime(); // Store current Time;
        while((new Date().getTime()-t)<mills);
    }
    

    所以在一个循环中,你可以使用我刚刚为你创建的sleep 函数。

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多