mcdcorp / opentest

Open source test automation tool for web applications, mobile apps and APIs
https://getopentest.org
MIT License
455 stars 110 forks source link

Executing JavaScript in the browser #616

Closed Keonik1 closed 1 year ago

Keonik1 commented 1 year ago

I don't understand how to call the code that I checked in the browser console. Example: I want to output the name of the current frame. In the temple, I open f12 -> console and enter: window.frames.name and in response I get my_name.

How to achieve the same effect in opentest?

I tried:

- script: var name = window.frames.name;
- script: $log(name);

and script: $log(window.frames.name); but it doesn't work, I get an error:

Caused by: java.lang.RuntimeException: Failed to evaluate JavaScript code at line number ?. The script content was: 
var name = window.frames.name
    at org.getopentest.base.TestActor.evalScript(TestActor.java:1490)
    at org.getopentest.base.ScriptAction.run(ScriptAction.java:32)
    at org.getopentest.base.TestActor.executeAction(TestActor.java:1571)
    at org.getopentest.base.TestActor.executeActionByDef(TestActor.java:1739)
    ... 4 more
Caused by: javax.script.ScriptException: ReferenceError: "window" is not defined in <eval> at line number 1

Could you write an example for this use?

adrianth commented 1 year ago

Script actions run in the context of the test actor process, not the browser, that's why the error says "window" is not defined. To run a script in the browser, you must use the ExecuteScript keyword, something like this:

- action: org.getopentest.selenium.ExecuteScript
  args:
    script: |
      return window.frames[0].name;

- script: $log("The frame name is " + $output.result)
Keonik1 commented 1 year ago

Thanks, I'll try it in a couple of days, if everything goes well, I'll close the issue

Keonik1 commented 1 year ago

Thanks, it worked!

If someone tries to copy, you may not be able to work, since the correct command for taking the name in my case is: return window.frames.name; Maybe you will also have