Nguyen Khoi Nguyen
Katalon Apprentice
11/20/2016

Execute javascript

Sometimes, I've met the element which is unable to click with the normal script by selenium so I have to use javascript to execute my script.

How can I write javascript on Katalon tool?

Upvote
Quote

Comments

  • Katalon Studio
    Katalon Moderator
    11/21/2016
    Hi,

    You can create 'Execute Javascript' custom keyword and use it in your test script directly:
    @Keyword
    def executeJavaScript(String javascript) {
    ((JavascriptExecutor) DriverFactory.getWebDriver()).executeScript(javascript)
    }
    We will consider adding a ticket to allow javascript execution as part of built-in keyword later.
    Upvote
    Quote
  • nguyen van nguyen
    Katalon Apprentice
    11/21/2016
    1. Follow your guidance, I've tried but It didn't work out. I imported the library java javascript:

    import org.openqa.selenium.JavascriptExecutor and write directly in my script

    ((JavascriptExecutor)WebUI).executeScript("myjavascript")

    2. When I execute it, Katalon showing the error message:

    Test Cases/Web UI/Demo/New Test Case FAILED because (of) org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords' with class 'java.lang.Class' to class 'org.openqa.selenium.JavascriptExecutor'

    Did I do something wrong or I need to do something else ?

    Would you please to help me
    Upvote
    Quote
  • Katalon Studio
    Katalon Moderator
    11/22/2016
    Hi,

    This segment of code is incorrect because you can't directly refer to WebUI class
    ((JavascriptExecutor)WebUI).executeScript(“myjavascript”)
    The current's instance of web driver must be used instead.
    Please change it to :

    ((JavascriptExecutor) DriverFactory.getWebDriver()).executeScript(“myjavascript”)
    Upvote
    Quote
  • Nguyen Khoi Nguyen
    Katalon Apprentice
    11/23/2016
    Hello follow your direction, but unfortunately I've still got error message. Here my demo script

    WebUI.openBrowser('')

    WebUI.navigateToUrl('m.sofitel.com')

    WebUI.click(findTestObject('Sofitel/Login_button'))

    WebUI.delay(5)

    ((JavascriptExecutor)ChromeDriver()).executeScript("document.getElementById(\'createaccount\').click()")

    WebUI.delay(5)

    WebUI.closeBrowser()

    Katalo is unable to execute my script with error message showing "Test Cases/New Test Case FAILED because (of) Variable 'DriverFactory' is not defined for test case."

    Do I need to create a class DirverFactory or Can I call from Katalon ?
    Upvote
    Quote
  • Katalon Studio
    Katalon Moderator
    11/24/2016
    Hi,

    Sorry for missing information. You need to import DriverFactory class if you its DriverFactory:
    import com.kms.katalon.core.webui.driver.DriverFactory;
    Thanks
    Upvote
    Quote
  • malkit singh
    Katalon Apprentice
    01/09/2017
    Hi,

    I imported DriverFactory as you mentioned but still I am getting unable to resolve class JavascriptExecutor error.
    Upvote
    Quote
  • Vinh Nguyen
    Katalon Moderator
    01/18/2017
    Please add this import to solve your case:
    import org.openqa.selenium.JavascriptExecutor;
    Upvote
    Quote
  • John Mathews
    Katalon Apprentice
    08/22/2017
    Hi All,

    I did both the imports as said above and used the following script but I get error: Can someone help please?

    ((JavascriptExecutor) driver).executeScript("document.getElementById('txtdepartdate').removeAttribute('readonly',0);");
    WebUI.setText(findTestObject('Page_ICON Electronic Booking Form/img_imgdepartdate'), '18-Aug-2017')
    Upvote
    Quote
  • Vinh Nguyen
    Katalon Moderator
    08/22/2017
    What is the error message from your side?
    Upvote
    Quote
  • John Mathews
    Katalon Apprentice
    08/23/2017
    the error message is this:

    Test Cases/IconBooking FAILED because (of) org.openqa.selenium.WebDriverException: document.getElementById(...) is null

     

    Note: IconBooking  is the name of my test case
    Upvote
    Quote
  • Robert Wierzbicki
    Katalon Apprentice
    10/21/2017

    What Katalon Studio wrote above works for me but also needed to add:
    import org.openqa.selenium.JavascriptExecutor
    import com.kms.katalon.core.webui.driver.DriverFactory as DriverFactory

    As a useless example in my test case I put
    CustomKeywords.'com.example.WebUICustomKeywords.executeJavaScript'('window.alert("test"); delay = 5000; var start = new Date().getTime(); while (new Date().getTime() < start + delay);')

    This shows an alert message of 'test' for 5 seconds before moving on.

    Upvote
    Quote
  • Balraj Alladi
    Katalon Apprentice
    10/31/2017

    You can use this custom function and can call any Test object which you want to click.

    Upvote
    Quote
  • Jhovanny Hernández
    Katalon Apprentice
    02/08/2018
    Thanks Balraj Alladi, I used your method and it works!
    Upvote
    Quote
  • tod2020@mail.ru
    Katalon Ambassador
    02/08/2018
    edited February 8
    How can i execute this Java-code(several line) for get All ID from class named "content" in page and get Katalon-Array?

    var everyChild =
    document.querySelectorAll(".content
    div");
    var result = [];
    for (var i = 0; i<everyChild.length; i++) {
        result[i]=everyChild[i].getAttribute('id');
    }
     console.log(result);

    Upvote
    Quote
  • P Satish Patnaik
    Katalon Apprentice
    02/21/2018
    Hi,Balraj Alladi 

    Can you give us the full program implemented using the custom function which you used so that we can follow the exact way and try to replicate?I am facing issue for a long time in date picker of android application, but not getting the solution, can anyone help me out in this ??
    Upvote
    Quote
  • Russ Thomas
    Katalon Evangelist
    04/10/2018
    edited April 10
    @Katalon Team

    Since this thread appears in the "Top Topics" listing, it should be pruned back to the original question and a single answer containing:

    Use WebUI.executeJavaScript

    https://docs.katalon.com/display/KD/[WebUI]+Execute+JavaScript

    The rest of this thread is at best "noise" and at worst "wrong".


    Upvote
    Quote
  • Diana
    Katalon Apprentice
    06/08/2018
    Hi,
    I got this message on step click an object to show innerpop.

    Test Cases/Setting/Login - Add FAILED because (of) Unable to click on object 'Object Repository/Page_Sys (1)/div_ADD' (Root cause: com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/Page_Sys (1)/div_ADD' located by 'By.xpath: //div[@id = 'ADD' and @title = 'Add']' not found)

    I already put delay after the click item.

    and use this script to show the inner pop

    WebUI.executeJavaScript('top.InnerPop', ['?xfid=hrm.setting.add'])

    WebUI.delay(1)

    but the inner pop still didn't show up.

    what should I do to resolve this?

    Thanks.
    Upvote
    Quote
  • test name
    Katalon Apprentice
    06/22/2018
    Hello, 

    I am facing one similar kind of issue while clicking on hyperlik from the webpage using katalon studio. I create test script using "Selenium C# in Visual studio" and able to run easily. So i don't know what is the issue in Katalon script

    Steps:
    1. open Url : https://jqueryui.com/
    2. Maximize the window
    3.  Click on "Draggable" link option under "Interactions"

    I am facing below issue

    Issue : 

    Test Cases/Functional Test/IframeTest FAILED because (of) org.codehaus.groovy.runtime.InvokerInvocationException: com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/Iframe/Page_Droppable  jQuery UI/a_Draggable' located by 'By.xpath: //a[@href = 'http://jqueryui.com/draggable/' and (text() = 'Draggable' or . = 'Draggable')]' not found

    utility.UtilityClass.invokeMethod:0
    Test Cases/Functional Test/IframeTest.run:36

    Please do the needful and guide me on that

    Upvote
    Quote
  • Jonathan Tzeng
    Katalon Apprentice
    07/13/2018
    I'm getting the following error when trying to use the javascript click:

    Test Cases/test1 FAILED because (of) org.openqa.selenium.WebDriverException: unknown error: arguments[0].click is not a function
    Upvote
    Quote
  • Russ Thomas
    Katalon Evangelist
    07/13/2018
    edited July 13
    arguments[0].click()

    Edit: Which is a misleading error message because the reference to the click method is typeof === "function".

    Regardless, you still need to add open and close parentheses to effect the call.

    Upvote
    Quote
  • Jonathan Tzeng
    Katalon Apprentice
    07/13/2018
    edited July 13
    arguments[0].click()

    Edit: Which is a misleading error message because the reference to the click method is typeof === "function".

    Regardless, you still need to add open and close parentheses to effect the call.

    Can you elaborate? I just basically copied what was out there on another thread. Still getting the hang of the syntax for javascript through JavascriptExecutor... 

    this is my package custom>clickJS.groovy:
    public class clickJS {
    def clickUsingJS(TestObject to) {
    WebDriver driver = DriverFactory.getWebDriver()
    WebElement element = WebUiCommonHelper.findWebElement(to, 30)
    JavascriptExecutor executor = ((driver) as JavascriptExecutor)
    executor.executeScript('arguments[0].click()', element)
    }
    }

    This is my usage in the test:
    CustomKeywords.'custom.clickJS.clickUsingJS'(findTestObject('target object'))

    Upvote
    Quote
  • Russ Thomas
    Katalon Evangelist
    07/13/2018
    Jonathan

    If you're going to use JS to target an element, go the whole hog and use JS directly on the page to hit the element.

    Here's the issue: Because you're using Katalon, you ended up with a Test Object.  Because you have a Test Object, you need to convert it to a Web Element.  Problem: JS doesn't know what the hell a TO is.  So, let's take a step back...

    JS can target the element directly.  That, in essence, is what JS is for.  You don't need all that TO stuff getting in your way.

    Give JS a CSS selector to the HTML element and then tell it to click the element.  It can find the element just fine without any need for Test Object/WebElement.

    void jsClicker(selector) {
      String js = '''
        document.querySelector(arguments[0]).click();
      '''
      WebUI.executeJavaScript(js, Arrays.asList(selector))
    }

    I use the triple-single-quote string so that it's easy to type out multi-line strings. Like this "wordy" version which does the exact same thing...

    void jsClicker(selector) {
      String js = '''
        var selector = arguments[0],
            elem = document.querySelector(selector);
        elem.click();
      '''
      WebUI.executeJavaScript(js, Arrays.asList(selector))
    }
    (Watch for typos, this code is right out of my head and untested).

    Let me know how you get on.

    @Katalon Team Because this thread is linked under "Top Topics" it keeps coming back. It's probably the worst thread on how to use JS in groovy. The first four or five message including those from "Katalon Moderator" are so outdated archeologists will be digging them up soon.

    Once again I implore you guys to edit this thread down and remove any extraneous/misleading/wrong examples. PLEASE.

    Upvote
    Quote
  • Russ Thomas
    Katalon Evangelist
    09/01/2018


    Upvote
    Quote
  • J. Bannister
    Katalon Apprentice
    09/07/2018
    edited September 7
    Hi @"Russ Thomas", I'm very new to Katalon, I need to execute a bit of javascript in my test but in my case what I need to do is set some element text, using your example above, I came up with this 

    void jsSetElementText(selector){
    String js = '''
    document.getElementById('receipt_item_amount_received_0').value = "4000" 
    '''
    }

    however I got the following error
    FAILED because (of) (Stack trace: groovy.lang.MissingPropertyException: No such property: js for class: Script1536083801544

    can you tell me where I went wrong?

    I found a work around for my situation and just in case this issue was not unique to me I just used the following: WebUI.executeJavaScript('document.getElementById(\'receipt_item_amount_received_0\').value = "4000" ', null)

    Upvote
    Quote
  • Russ Thomas
    Katalon Evangelist
    09/07/2018
    edited September 7
    Hi Gavin

    void jsSetElementText(selector){
     String js = '''
     document.getElementById('receipt_item_amount_received_0').value = "4000"
    '''
    }

    That method merely builds a string and then does nothing with it.

    This might be what you're trying to achieve...

    void jsSetText(String selector, String val) {
      String js = '''
        var selector = arguments[0],
    val = arguments[1],
            elem = document.querySelector(selector);
        elem.value = val;
      '''
      WebUI.executeJavaScript(js, Arrays.asList(selector, val))
    }
    I have not checked this but it looks okay from here  B)
    Upvote
    Quote
Sign In or Register to comment.