Search code examples
pythonseleniumselenium-webdriversafaridriver

How to initialize JS variables through Selenium python?


I am trying to execute a JS file through python, selenium but I think I miss something.

I tried to call the checking variable from safari console, but it shows the following error Can't find the checking variable.

I also tried to execute the following code line driver.execute_script('var checking=0;') but I got the same result when I tried to call the checking variable from Safari Console.

PYTHON CODE

driver.execute_script(open("/Users/Paul/Downloads/pythonProject/Social media/javascripts/Initializing Variables.js").read())

JS FILE

var checking;
function Checking(item) {
    if (item) {
        checking = true;
    }
    else {
        checking = false;
    }
}

Any ideas?


Solution

  • All variables will be available just in single execute_script command context. So it's not possible to define variable in one driver command and modify it or get by another, unless you put the data to document, localstorage or sessionstorage..

    But you're able to declare and put something to the variable, just don't forget to return it's value in script.

    If I execute this script with driver.execute_script

    var a;
    function setAValue(arg) {
        a = arg;
    }
    
    setAValue(100);
    return a;
    

    you'll get 100 in the output result.

    And if you want to run your file from script, the file should ends with the function invocation and the return statement.

    Share function and variables between scripts

    This is working example in groovy language (sorry no python env)

    WebDriverManager.chromedriver().setup()
    WebDriver driver = new ChromeDriver()
    
    driver.get("https://stackoverflow.com/")
    //define variable date and function GetTheDatesOfPosts 
    driver.executeScript('''
        document.date = [];
        document.GetTheDatesOfPosts = function (item) { document.date = [item];}
    ''')
    
    //use them in new script
    println (driver.executeScript('''
        document.GetTheDatesOfPosts(7);
        return document.date;
        '''))
    driver.quit()
    

    it prints [7].