How to highlight an element on the webpage?

Hi,

OS: Windows 10 Pro

Katalon Studio Version: 5.3.1

Browser: Chrome - Version: 65.0.3325.181

Is there a command to highlight an element during execution so that it briefly changes the background color of the specified element to yellow?

Thank you!

Hi Divya ,

There is no such inbuilt keyword. You have to create custom keyword.
Right Click on Keyword Folder and click new keyword. code editor will open.

Now add below code and save it -

@Keyword
    def highlightObject(TestObject to){
        WebElement element = WebUiCommonHelper.findWebElement(to, 30)
        WebUI.executeJavaScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", Arrays.asList(
               element))
        WebUI.delay(1);
        WebUI.executeJavaScript("arguments[0].setAttribute('style','border: solid 2px white');", Arrays.asList(
               element));

Now go to your test case and click on add button and select custom UI keyword.
Now select custom keyword that is created recently.
Pass element object which you want to highlight. It will work perfectly.

Regards,
Himanshu

5 Likes

Kindly vote my comment if your query is answered.

1 Like

Hi Himanshu,

Thank you for the code.

But I see ‘Groovy:unable to resolve class Web element’ on line (WebElement element = WebUiCommonHelper.findWebElement(to, 30)

Thanks again!

Hello All,

Here is a way to do it.

  1. In Katalon, go to Keywords folder.
  2. Create a package and call it, com.reusableComponents
  3. Create a keyword and call it, HighlightElement
  4. Copy and paste this code in your keyword.
  5. In Katalon Add > Custom Keyword, Select com.reusableComponents.HighlightElement.run and in the object Column

Copy code
---------------------------------------------------------------------

package com.reusableComponents

import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.testng.Assert
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.common.WebUiCommonHelper
import com.kms.katalon.core.webui.driver.DriverFactory

public class HighlightElement {

    static WebDriver driver = DriverFactory.getWebDriver()

    @Keyword
    public static void run(TestObject objectto) {
        try {
            WebElement element = WebUiCommonHelper.findWebElement(objectto, 20);
            for (int i = 0; i < 5; i++) {
                JavascriptExecutor js = (JavascriptExecutor) driver;
                js.executeScript("arguments\[0\].setAttribute('style','background: yellow; border: 5px solid red;');", element);
            }
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
    }
}
5 Likes

@Bob H. Thanks for your update. your code was perfectly working.

1 Like

Bob H said:

Hello All,

Here is a way to do it.

  1. In Katalon, go to Keywords folder.
  2. Create a package and call it, com.reusableComponents
  3. Create a keyword and call it, HighlightElement
  4. Copy and paste this code in your keyword.
  5. In Katalon Add > Custom Keyword, Select com.reusableComponents.HighlightElement.run and in the object Column

Copy code
---------------------------------------------------------------------

package com.reusableComponents

import org.openqa.selenium.JavascriptExecutor

import org.openqa.selenium.WebDriver

import org.openqa.selenium.WebElement

import org.testng.Assert

import com.kms.katalon.core.annotation.Keyword

import com.kms.katalon.core.testobject.TestObject

import com.kms.katalon.core.webui.common.WebUiCommonHelper

import com.kms.katalon.core.webui.driver.DriverFactory

public class HighlightElement {

static WebDriver driver = DriverFactory.getWebDriver()

@Keyword

public static void run(TestObject objectto) {

try {

WebElement element = WebUiCommonHelper.findWebElement(objectto, 20);

    for (int i = 0; i < 5; i++) {

        JavascriptExecutor js = (JavascriptExecutor) driver;

        js.executeScript("arguments\[0\].setAttribute('style','background: yellow; border: 5px solid red;');",

                element);

    }

} catch (Exception e) {

    Assert.fail(e.getMessage());

}

}

}

Thanks Bob . It is working . Could you please suggest ,why are you using For loop when you havent using the variable ‘i’ in your code?

Bob’s code was perfect.

Minimal modification to utilize for loop and make it appears as if it’s blinking:

for (int i = 0; i < 50; i++) {

 JavascriptExecutor js = (JavascriptExecutor) driver;

 js.executeScript("arguments\[0\].setAttribute('style','background: gray;');",element);

 js.executeScript("arguments\[0\].setAttribute('style','background: clear;');",element);  

}

Hi All,

Create a custom keyword using below package name and code. you can call it that custom keyword and highlight the element.

Highlight element code:
Package name: com.reusableComponents

package com.reusableComponents

import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint

import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject

import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.checkpoint.Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords
import com.kms.katalon.core.model.FailureHandling
import com.kms.katalon.core.testcase.TestCase
import com.kms.katalon.core.testcase.TestCaseFactory
import com.kms.katalon.core.testdata.TestData
import com.kms.katalon.core.testdata.TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords

import internal.GlobalVariable

import MobileBuiltInKeywords as Mobile
import WSBuiltInKeywords as WS
import WebUiBuiltInKeywords as WebUI

import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.testng.Assert

import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.common.WebUiCommonHelper
import com.kms.katalon.core.webui.driver.DriverFactory

public class HighlightElement {

static WebDriver driver = DriverFactory.getWebDriver()

@Keyword
public static void run(TestObject objectto) {
	try {
		WebElement element = WebUiCommonHelper.findWebElement(objectto, 20);
		for (int i = 0; i < 5; i++) {
			JavascriptExecutor js = (JavascriptExecutor) driver;
			js.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');",
					element);
		}
	} catch (Exception e) {
		Assert.fail(e.getMessage());
	}
}

}

1 Like

The wheel was reinvented at

Hello everyone,

I tried to create a method to highlight a text (String) on the current page. I got inspired using the above code but an error occurred when I tried to run it.

The code is the following:

public class HighlightText {
	static WebDriver driver = DriverFactory.getWebDriver()
	@Keyword
	public static void highlightText(String text){
		boolean textExist = WebUiCommonHelper.isTextPresent(driver, text, true);
		try {
			if(textExist == true){
				for (int i = 0; i < 5; i++) {
					JavascriptExecutor js = (JavascriptExecutor) driver
					js.executeScript("arguments[0].setAttribute('style','background: yellow; border: 2px solid red;');",
							text)
				}
			}
		} catch (Exception e) {
			Assert.fail(e.getMessage())
		}
	}
}

I got he following error.

com.methods.HighlightText.highlightText("Submitted") FAILED.
Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.AssertionError: unknown error: arguments[0].setAttribute is not a function
os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_181'
Driver info: com.kms.katalon.selenium.driver.CChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.43.600210 (68dcf5eebde371..., userDataDir: C:\Users\WANGHO~1\AppData\L...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:52561}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 73.0.3683.103, webStorageEnabled: true}
Session ID: 9da1472f4acba4a20495ebe6e620d6ab
	at com.methods.HighlightText.invokeMethod(Methods.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:49)
	at Portal Auto-Approve Normal Case.run(Portal Auto-Approve Normal Case:148)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:328)
	at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:319)
	at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:298)
	at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:290)
	at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:224)
	at com.kms.katalon.core.main.TestSuiteExecutor.accessTestCaseMainPhase(TestSuiteExecutor.java:129)
	at com.kms.katalon.core.main.TestSuiteExecutor.accessTestSuiteMainPhase(TestSuiteExecutor.java:112)
	at com.kms.katalon.core.main.TestSuiteExecutor.execute(TestSuiteExecutor.java:81)
	at com.kms.katalon.core.main.TestCaseMain.startTestSuite(TestCaseMain.java:149)
	at com.kms.katalon.core.main.TestCaseMain$startTestSuite$0.call(Unknown Source)
	at TempTestSuite1555093574563.run(TempTestSuite1555093574563.groovy:36)
Caused by: java.lang.AssertionError: unknown error: arguments[0].setAttribute is not a function
  (Session info: chrome=73.0.3683.103)
  (Driver info: chromedriver=2.43.600210 (68dcf5eebde37173d4027fa8635e332711d2874a),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
System info: host: 'QCMONTC661582P', ip: '10.135.45.32', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_181'
Driver info: com.kms.katalon.selenium.driver.CChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.43.600210 (68dcf5eebde371..., userDataDir: C:\Users\WANGHO~1\AppData\L...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:52561}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 73.0.3683.103, webStorageEnabled: true}
Session ID: 9da1472f4acba4a20495ebe6e620d6ab
	at org.testng.Assert.fail(Assert.java:93)
	at org.testng.Assert$fail.call(Unknown Source)
	at com.methods.HighlightText.highlightText(Methods.groovy:70)
	at com.methods.HighlightText.invokeMethod(Methods.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:49)
	at Script1554317572990.run(Script1554317572990.groovy:148)
	... 13 more

I read online that "arguments[0].setAttribute()" can only be used with WebElement objects. I tried looking up online to see how i could use it for String variables, but to no success.

Any help would be appreciated!

PLS have a look at this:

2 Likes

line 22-36 of https://github.com/kazurayam/HighlightingElementByTestObjectInEachAndEveryStep/blob/master/Keywords/com/kazurayam/ksbackyard/HighlightElement.groovy may be interesting for you.

Hi,

I don’t know how it works ?

I wrote your HighlightElement Class but i don’t know how to call it for my List and for Object too.
This is my script :

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject

import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement

import com.kms.katalon.core.webui.driver.DriverFactory
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

WebUI.navigateToUrl(‘https://www.pagesjaunes.fr/’)

WebUI.setText(findTestObject(‘Pagesjaunes/Page_Accueil/input_quoi qui _quoiqui’),
‘architecte’)

WebUI.setText(findTestObject(‘Pagesjaunes/Page_Accueil/input_o _ou’),
‘ile-de-france’)

WebUI.click(findTestObject(‘Pagesjaunes/Page_Accueil/i_A proximit_icon icon-search’))

//CrĂ©ation d’un objet Email:
/TestObject button_email = new TestObject(‘Email Button’)
a=2
button_confirm.addProperty(‘title’, ConditionType.EQUALS, ‘E-Mail’)
WebUI.click(button_confirm)
a=1
/
WebUI.delay(5)
//aide brandon_hein
WebDriver driver = DriverFactory.getWebDriver()
List buttons = driver.findElements(By.xpath(“//a[@title=‘E-Mail’]”))
println buttons.size()

buttons.get(0).click()

WebUI.delay(5)

Hi there @ouknam!

I see, you did right creating the reusable component.

Now, for you to be able to use the HighlightElement you need to feed it with the element/object that you want to highlight.

The syntax for this should be like: CustomKeywords.'com.reusableComponents.HighlightElement.run'(objectThatYouWantToHighlight)
WebUI.click(objectThatWasHighlighted)

With this, it would highlight the element/object before it performs the click action.

What exactly are you trying to highlight in your code, @ouknam?

It’s a List of Email button :

buttons.get(i).click()

I don’t know how to ?

When i try this :

List <WebElement> buttons = driver.findElements(By.xpath('//a[@title=\'E-Mail\']'))
for ...
CustomKeywords.'com.reusableComponents.HighlightElement.run'(buttons.get(i).click())
	WebUI.delay(10)
	buttons.get(i).click()

...
}}

I have this error :

08-15-2019 10:49:41 PM Test Cases/TC_Principale

Elapsed time: 21,019s

Test Cases/TC_Principale FAILED.
Reason:
org.codehaus.groovy.runtime.metaclass.MissingMethodExceptionNoStack: No signature of method: com.reusableComponents.HighlightElement.run() is applicable for argument types: (null) values: [null]
Possible solutions: any(), find(), grep(), dump(), is(java.lang.Object), any(groovy.lang.Closure)

I implemented this code (Bob’s excellent HighlightElement code), but it would throw errors when running multiple tests in a test suite. I’d see an error

at com.reusableComponents.HighlightElement.invokeMethod 

java.lang.AssertionError: Session ID is null. Using WebDriver after calling quit()?

I modified Bob’s code according to this suggestion, moving the actual getWebDriver call deeper in:

Getting the driver each time might be less efficient, but it definitely stopped my errors.

Hello @Bob_H, your code for highlightElement is perfectly working in a single Test case. But it is not working if I use it in a Test Suite. Do you have any recommendation how to fix it? Thanks

Maybe I’m not seeing what is the concern, but a Test Suite is just a bunch of Test Cases. So how have you made it different that the “highlightObject” method that is run from a Custom Keyword does not work in each of the Test Cases of the Test Suite? Or, are you using a TestListener to set it up or some other such?

the concern is, you perform ‘testing’ for oohs and aaahs.
decouple yourself from this and start to write tests to actually validate something.
ignore the PM’s, think from a technicall perspective.
you may find out eventually that ‘highlighing element’ is just bling bling with no real benefit.