Does Katalon Studio have some functions like "Verify last console output"?

For example, suppose I need to test a canvas-based web page (eg: a game), after pressing a button on the canvas, the console would output a statement for example : console.log(“Button A pressed”); , does Katalon Studio have some functions that assert if the last output string of the console is “Button A pressed”?

1 Like

hi @maxfair

why don’t you create one using custom keywords?
claude code gave me this example to try:

package com.example.keywords

import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.webui.driver.DriverFactory
import org.openqa.selenium.WebDriver
import org.openqa.selenium.logging.LogEntry
import org.openqa.selenium.logging.LogType

public class ConsoleLogKeywords {
    
    private static List<LogEntry> cachedLogs = []
    
    @Keyword
    def getConsoleLogs(boolean clearCache = true) {
        WebDriver driver = DriverFactory.getWebDriver()
        List<LogEntry> logs = driver.manage().logs().get(LogType.BROWSER).getAll()
        
        if (clearCache) {
            cachedLogs = logs
        } else {
            cachedLogs.addAll(logs)
        }
        return cachedLogs
    }
    
    @Keyword
    def verifyLastConsoleMessage(String expectedMessage, boolean exactMatch = false) {
        def logs = getConsoleLogs()
        
        if (logs.isEmpty()) {
            throw new AssertionError("No console logs found")
        }
        
        String lastMessage = logs.last().getMessage()
        
        if (exactMatch) {
            assert lastMessage == expectedMessage : "Expected: '${expectedMessage}' but got: '${lastMessage}'"
        } else {
            assert lastMessage.contains(expectedMessage) : "Console log doesn't contain '${expectedMessage}'. Got: '${lastMessage}'"
        }
        
        return true
    }
    
    @Keyword
    def verifyConsoleContains(String expectedMessage) {
        def logs = getConsoleLogs()
        boolean found = logs.any { it.getMessage().contains(expectedMessage) }
        
        assert found : "No console log containing '${expectedMessage}' found"
        return true
    }
    
    @Keyword
    def waitForConsoleMessage(String expectedMessage, int timeoutSeconds = 10) {
        long endTime = System.currentTimeMillis() + (timeoutSeconds * 1000)
        
        while (System.currentTimeMillis() < endTime) {
            def logs = getConsoleLogs(false)
            if (logs.any { it.getMessage().contains(expectedMessage) }) {
                return true
            }
            Thread.sleep(500)
        }
        
        throw new AssertionError("Console message '${expectedMessage}' not found within ${timeoutSeconds}s")
    }
}

save this to Keywords/com/example/keywords/ConsoleLogKeywords.groovy and use it like:

// Click your canvas button
WebUI.click(findTestObject('Page_Game/canvas_game'))

// Then verify
CustomKeywords.'com.example.keywords.ConsoleLogKeywords.verifyLastConsoleMessage'('Button A pressed')

// Or if timing is unpredictable:
CustomKeywords.'com.example.keywords.ConsoleLogKeywords.waitForConsoleMessage'('Button A pressed', 5)

There’s no built‑in “Verify last console output” keyword in Katalon Studio, but you can achieve it easily with a small custom keyword that reads the browser console logs via WebDriver as explained above

What do you mean by “console”?

Do you mean it the console object in JavaScript language? something like:

Or is it the “Console” tab visible in the Katalon Studio GUI?


I believe that @depapp was talking about the Console tab of Katalon Studio GUI. If @maxfair want to read the message emitted by console.log(msg) in Javascript of the web page under test, @depapp’s suggestion will fall besides the point.

If @maxfair wants to read the message emitted by console.log(msg) in JavaScript, unfortunately Katalon Studo does not provide a way to do that easily.


There were several hacks previously discussed, but these were too much complicated. See

or

The previous discussion might not work today with the recent Katalon and browser versions.

As explained in Exploring Selenium BiDi Functionality | Awesome Testing , Selenium 4 supports Chrome DevTools protocol (CDP) which Katalon Studio v10 runs upon. With CDP, the console message should be accessible for the API clients. However I don’t know if it is possible for tests in Katalon Studio to listen to javascript errors in console. Katalon has not published any tutorial how to use CDP features in Katalon Studio v10. I suppose it would be tough to try it out.

By the way, using Playwright, you can achieve what you want to do easily. See

@maxfair your query resolved?

Hi @maxfair,

Have you got your issue answered? If yes, feel free to share how to. If no, let us know more information and we would love to help. Best

Solutions

Solution 1: Intercept Console Output Using JavaScript (Recommended)

Source: WebUI.executeJavaScript Documentation

This approach intercepts console.log() calls and stores them in a variable that you can then verify:

Step 1: Create a custom keyword to capture console output

@Keyword
def captureConsoleOutput() {
    // Initialize console capture before any actions
    WebUI.executeJavaScript("""
        window.capturedLogs = [];
        const originalLog = console.log;
        console.log = function(...args) {
            window.capturedLogs.push(args.join(' '));
            originalLog.apply(console, args);
        };
    """, null)
}

@Keyword
def getLastConsoleLog() {
    // Get the last console.log output
    Object lastLog = WebUI.executeJavaScript("""
        return window.capturedLogs ? window.capturedLogs[window.capturedLogs.length - 1] : null;
    """, null)
    return lastLog
}

@Keyword
def getAllConsoleLogs() {
    // Get all captured console logs
    Object allLogs = WebUI.executeJavaScript("""
        return window.capturedLogs ? window.capturedLogs : [];
    """, null)
    return allLogs
}

@Keyword
def assertConsoleLogContains(String expectedText) {
    Object lastLog = getLastConsoleLog()
    if (lastLog == null) {
        throw new Exception("No console logs captured")
    }
    if (!lastLog.toString().contains(expectedText)) {
        throw new Exception("Expected console log to contain: '${expectedText}', but got: '${lastLog}'")
    }
    return true
}

Step 2: Use in your test case

import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

// Open browser and navigate to canvas-based page
WebUI.openBrowser('')
WebUI.navigateToUrl('your-canvas-game-url')

// Initialize console capture
CustomKeywords.'your.package.ConsoleCapture.captureConsoleOutput'()

// Perform action on canvas (e.g., click button)
WebUI.click(findTestObject('Pages/Canvas/ButtonA'))

// Wait a moment for the console.log to execute
WebUI.delay(1)

// Assert the console output
CustomKeywords.'your.package.ConsoleCapture.assertConsoleLogContains'('Button A pressed')

// Or get and verify the last log
String lastLog = CustomKeywords.'your.package.ConsoleCapture.getLastConsoleLog'()
WebUI.verifyEqual(lastLog, 'Button A pressed')

WebUI.closeBrowser()

Solution 2: Direct JavaScript Assertion (Inline)

If you prefer a one-liner approach without creating a custom keyword:

// Initialize console capture
WebUI.executeJavaScript("""
    window.capturedLogs = [];
    const originalLog = console.log;
    console.log = function(...args) {
        window.capturedLogs.push(args.join(' '));
        originalLog.apply(console, args);
    };
""", null)

// Click button on canvas
WebUI.click(findTestObject('Pages/Canvas/ButtonA'))
WebUI.delay(1)

// Verify the last console output
String lastLog = WebUI.executeJavaScript("""
    return window.capturedLogs ? window.capturedLogs[window.capturedLogs.length - 1] : null;
""", null)

WebUI.verifyEqual(lastLog, 'Button A pressed')

Solution 3: For Canvas Element Interaction

Since you’re testing a canvas-based page, you’ll also need to interact with canvas elements using coordinates:

Source: Canvas Automation Documentation

// Canvas elements require coordinate-based interaction
// Find the canvas element
WebElement canvas = WebUiCommonHelper.findWebElement(findTestObject('Pages/Canvas/GameCanvas'), 30)

// Get canvas coordinates and click at specific position
WebUI.executeJavaScript("""
    const canvas = arguments[0];
    const rect = canvas.getBoundingClientRect();
    const x = rect.left + 100;  // Adjust coordinates as needed
    const y = rect.top + 50;
    
    // Simulate click at coordinates
    const event = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
        clientX: x,
        clientY: y
    });
    canvas.dispatchEvent(event);
""", Arrays.asList(canvas))

// Then verify console output
String lastLog = WebUI.executeJavaScript("""
    return window.capturedLogs ? window.capturedLogs[window.capturedLogs.length - 1] : null;
""", null)

WebUI.verifyEqual(lastLog, 'Button A pressed')

Key Points

Aspect Details
Built-in Console Assertion :cross_mark: Katalon does NOT have a native keyword for this
Recommended Approach :white_check_mark: Use WebUI.executeJavaScript() with console interception
Return Types String, Boolean, Long, Double, List, WebElement, or Null
Canvas Interaction Use coordinate-based clicks via JavaScript or WebUI.executeJavaScript()
Verification Use WebUI.verifyEqual() or custom assertions

Complete Working Example

import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import com.kms.katalon.core.webui.common.WebUiCommonHelper
import java.util.Arrays

// Open browser
WebUI.openBrowser('')
WebUI.navigateToUrl('https://your-canvas-game.com')

// Setup console capture
WebUI.executeJavaScript("""
    window.capturedLogs = [];
    const originalLog = console.log;
    console.log = function(...args) {
        window.capturedLogs.push(args.join(' '));
        originalLog.apply(console, args);
    };
""", null)

// Find and click canvas button
WebElement canvas = WebUiCommonHelper.findWebElement(findTestObject('Pages/Canvas/GameCanvas'), 30)
WebUI.executeJavaScript("""
    const canvas = arguments[0];
    const rect = canvas.getBoundingClientRect();
    const clickEvent = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window,
        clientX: rect.left + 100,
        clientY: rect.top + 50
    });
    canvas.dispatchEvent(clickEvent);
""", Arrays.asList(canvas))

WebUI.delay(1)

// Verify console output
String lastLog = WebUI.executeJavaScript("""
    return window.capturedLogs[window.capturedLogs.length - 1];
""", null)

WebUI.verifyEqual(lastLog, 'Button A pressed', FailureHandling.STOP_ON_FAILURE)

WebUI.closeBrowser()

This approach gives you full control over console output verification for canvas-based applications!

1 Like

Please find my essay about capturing console log by LogInspector of Selenium 4: