Tales Pádua
Tales Pádua

Reputation: 1461

How to execute a JavaScript function defined in the website script with Selenium?

I am working with a website and I need to run a couple js code with Selenium. To make things easier, I need to run functions declared in the website scripts.
For example, the website use a script file called document_handler.js with the following code:

 (function ($) {
     var getConversationId = function(){
         return $('input[name="conversationId"]').val()
     };
 })(jQuery);

In Selenium, if I run:

js_eval = driver.execute_script("return getConversationId()")

I get:

selenium.common.exceptions.WebDriverException: Message: getConversationId is not defined

And if I run:

js_eval = driver.execute_script("return $.getConversationId()")

I get:

selenium.common.exceptions.WebDriverException: Message: $.getConversationId is not a function

How can I load the website javascript files so I can use its functions inside Selenium? Or there is something wrong with my code?

Upvotes: 2

Views: 5160

Answers (1)

webdeb
webdeb

Reputation: 13211

If this is a script you have access to, you have to make the function available to the outer/global scope.. The simplest would be to assign it to the window object, and it should work.

(function ($) {
     window.getConversationId = function(){
         return $('input[name="conversationId"]').val()
     };
 })(jQuery);

OR this way, which is basically the same..

var getConversationId;
(function ($) {
     getConversationId = function(){
         return $('input[name="conversationId"]').val()
     };
 })(jQuery);

Upvotes: 1

Related Questions