Pass variable to javascript for execution

Hello,

I am trying to pass a variable defined in my script to some javascript code, ran using execute Javascript keyword. Is this possible?

myvariable='sometext'
WebUI.executeJavaScript("alert(myvariable)", null)

The error I get running something like above is:

Test Cases/whole booking scenario FAILED because (of) Unable to execute JavaScript. (Root cause: org.openqa.selenium.WebDriverException: unknown error: myvariable is not defined

How can I let the javascript know what my variable is?

(Worth noting that my variable is dynamically generated unlike example code above)

Thank you

1 Like

Anthony,

this is what you want:

String myvariable='sometext'String myJs = "alert(\"" + myvariable + "\")"WebUI.executeJavaScript(myJs, null)

Explanation: JS alert method takes String as a parameter, so it must be enclosed in quotes.
BUT - if you want to pass variable from Katalon, you must go out from String and use + sign to concat variable to the rest of JS string.

Plain myJs value (after all replacements) is then **alert(“sometext”)

**To prevent confusion of escaping doublequotes in myJs variable, you can use singlequotes for defining String in Katalon, like this:

String myJs = 'alert("' + myvariable + '")'
1 Like

Marek Melocik said:

Anthony,

this is what you want:

String myvariable='sometext'String myJs = "alert(\"" + myvariable + "\")"WebUI.executeJavaScript(myJs, null)

Explanation: JS alert method takes String as a parameter, so it must be enclosed in quotes.  
BUT - if you want to pass variable from Katalon, you must go out from String and use + sign to concat variable to the rest of JS string.  
  
Plain myJs value (after all replacements) is then **alert("sometext")  
  
**To prevent confusion of escaping doublequotes in myJs variable, you can use singlequotes for defining String in Katalon, like this:

String myJs = ‘alert("’ + myvariable + ‘")’


  

Fantastic, thank you for clear and concise answer