pi 4q
pi 4q

Reputation: 23

reload iframe and click button inside iframe as much as I want

window.onhashchange = function () {
        window.setTimeout(function () {
            let frame = document.querySelector("body > iframe");
            if (frame !== null) {frame.replaceWith(frame);}
        }, 1000);
    }
//reload the iframe
var i = 0;
while (i < 100) {
    async function DStuff(){
        await document.querySelector("#Btn").click()
    }
    setTimeout(() => { DStuff() }, 3000)
    window.onhashchange();
    i++;
}
//click button

I want to refresh iframe and click button as much as I want. When I run this script it doesn't loop. Also the script should wait for a second after click the button.

Upvotes: 0

Views: 171

Answers (2)

DBS
DBS

Reputation: 9984

If you want to use a different time delay between the reload and the click, you can use two functions that recursively call each other, with a count to stop the loop:

var totalIterations = 0;

function clickButton() {
  console.log("clickButton called")
  
  // Your Click-button code here
  //document.querySelector("#Btn").click()
  
  // In 1 second, call the reload frame function
  setTimeout(reloadFrame, 1000)
}

function reloadFrame() {
  console.log("reloadFrame called")
  
  // Your Reload-frame code here:
  //let frame = document.querySelector("body > iframe");
  //if (frame !== null) { frame.replaceWith(frame); }
  
  // If we haven't run 100 times yet, run the click button in 3 seconds
  if (totalIterations < 100) {
    setTimeout(clickButton, 3000)
    totalIterations++
  }
}

// Call the function to start
clickButton()

Upvotes: 1

Ivan
Ivan

Reputation: 1314

Drop the loop and simply use a setInterval:

window.onhashchange = function () {
        window.setTimeout(function () {
            let frame = document.querySelector("body > iframe");
            if (frame !== null) {frame.replaceWith(frame);}
        }, 1000);
    }
//reload the iframe

var i = 0;   
let myVar = setInterval(function(){ 
  i++;
  document.querySelector("#Btn").click();
  window.onhashchange();
  if (i === 100) {
    clearInterval(myVar);
  }
},3000);   

The above waits for 3 seconds until it clicks again while it stops after reaching 100 clicks. Needless to say, the iFrame must be on the same domain, otherwise it won't be accessible due to cross-site restriction.

Upvotes: 1

Related Questions