3

I'm trying to call an existing javascript function on the page but I'm not getting it.

This is the element I have:

<area shape="rect" coords="513,0,580,66" href="#" onclick="document.f2.submit();">

This is the call:

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("document.f2.submit()");

Exception:

unknown error: Cannot read property 'submit' of undefined
(Session info: chrome=55.0.2883.87)
(Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 6.1.7601 SP1 x86_64)

How can I perform this operation normally?

5
  • looks like the script is executing but document.f2 doesn't point to anything, are you sure that part works when executed in the browser? Commented Jan 2, 2017 at 11:59
  • Yes, I tested via chrome console and ran normally Commented Jan 2, 2017 at 12:10
  • it might be executing too early then, have you tried executing js.ExecuteScript("setTimeout(function() { document.f2.submit(); }, 1000);");? the idea is to execute the script after some time to ensure that everything is "in place" Commented Jan 2, 2017 at 12:25
  • Works great, really thanks :) Commented Jan 2, 2017 at 12:30
  • I will post it as an answer if you don't mind Commented Jan 2, 2017 at 12:34

1 Answer 1

3

It sometimes happens that the script executes too early and some elements in the page are not in place yet (thus giving errors).

The best thing to do in these cases is to execute the script after some time has passed in order to determine that that is really the problem.

js.ExecuteScript("setTimeout(function() { document.f2.submit(); }, 1000);");

After confirming that the problem really is timing, the next thing to do is figure out when to perform the script injection so that the element is in the page and there's no problem (and thus you can remove the setTimeout from the script injection and leave only the operation you wanted to perform initially).

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

Comments

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.