2

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?

3
  • is it obterConversationId or getConversationId ? Commented Jul 11, 2016 at 20:42
  • 1
    However, the function is in a closed scope, you cannot access it, even from the console.. Commented Jul 11, 2016 at 20:43
  • @webdeb fixed, it was a typo Commented Jul 11, 2016 at 20:46

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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
Can this be wrapped in a JSE call?
@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 ;)
You can change the modified script only on the webserver but that does not seem intended.
I will try to change the script and inject it following this question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.