6

I am trying to create and execute a JavaScript function with Selenium. I am doing it like this:

js_func = """
     function blah(a, b, c) {
        .
        .
        .
};
"""
self.selenium.execute_script(js_script)
self.selenium.execute_script("blah", 1,2,3)

I don't get any errors from the first one (creating the function), but the second one gives me:

WebDriverException: Message: u'blah is not defined'

Is what I'm doing valid? How I can tell if the function was successfully created? How can I see the errors (assuming there are errors)?

1 Answer 1

13

It's just how Selenium executes JavaScript:

The script fragment provided will be executed as the body of an anonymous function.

In effect, your code is:

(function() {
    function blah(a, b, c) {
        ...
    }
})();

(function() {
    blah(1, 2, 3);
});

And due to JavaScript's scoping rules, blah doesn't exist outside of that anonymous function. You'll have to make it a global function:

window.blah = function(a, b, c) {
    ...
}

Or execute both scripts in the same function call.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Defining the script and calling in the same execute_script call worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.