1

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?

Tales Pádua
  • 1,331
  • 1
  • 16
  • 36

1 Answers1

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);
webdeb
  • 12,993
  • 5
  • 28
  • 44
  • This is a Script loaded by the page, not written by me. I can download it and edit, but I am not sure how to make Selenium load the edited script and ignore the original – Tales Pádua Jul 11 '16 at 20:54
  • Can this be wrapped in a JSE call? – JeffC Jul 11 '16 at 20:59
  • @TalesPádua I would love to answer you the special selenium question with script replacing??, but I not an expert, you should open a new question and describe the problem more precisely, don't forget to vote and accept ;) – webdeb Jul 11 '16 at 21:00
  • You can change the modified script only on the webserver but that does not seem intended. – Jeroen Heier Jul 11 '16 at 21:00
  • I will try to change the script and inject it following this [question](http://stackoverflow.com/questions/17385779/how-do-i-load-a-javascript-file-into-the-dom-using-selenium) – Tales Pádua Jul 11 '16 at 21:03