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

时间:2016-07-11 20:38:49

标签: javascript python selenium selenium-webdriver

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?

1 个答案:

答案 0 :(得分:1)

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);