pythonseleniumselenium-webdriverselenium-chromedriver

python selenium how to execute_script only when function is available


I want to do driver.execute_script('getDate();')

This function getDate() is defined in the javascript of the webpage. How to make sure that the function definition has loaded first? Otherwise I get an error saying javascript error: no such function...

Update: My use case is that there is a datepicker element that calls this function at some point. I would like to directly get/set the date with this function rather that writing code to find the datepicker element, click on day,month,year etc which I feel would be complicated


Solution

  • You can try using a wait until with the following:

    // waituntil
    while (typeof getDate !== "function") {
      task(i); // timeout
    }
    
    function task(i) {
      setTimeout(function() {
          // Add tasks to do
      }, 2000 * i);
    }
    
    // now call getDate
    getDate();