balin / com.github.epadronu.balin.core / JavaScriptExecutor

JavaScriptExecutor

interface JavaScriptExecutor

Describes an easier way to interact with JavascriptExecutor.executeScript & JavascriptExecutor.executeAsyncScript, allowing the execution of synchronous and asynchronous JavaScript code if such functionality is supported by the underlying driver.

Synchronous code

Browser.drive(driverFactory = driverFactory) {
    // When I navigate to the Kotlin's page URL
    to("https://kotlinlang.org/")

    // And I execute JavaScript code with arguments via `invoke`
    val arguments = js(1.5, 2.3) {
        "return 'Arguments: ' + arguments[0] + ', ' + arguments[1];"
    }

    // Then I should get the arguments as is
    assertEquals(arguments, "Arguments: 1.5, 2.3")
}
// Given I create a 100-elements array to be passed as arguments to the script
val arguments = Array(100) { it }

Browser.drive(driverFactory = driverFactory) {
    // When I navigate to the Kotlin's page URL
    to("https://kotlinlang.org/")

    // And I execute an asynchronous JS code to get how many arguments I passed to it
    val argumentsLength = js(*arguments, async = true) {
        """
            var argumentsLength = arguments.length - 1;

            var callback = arguments[arguments.length - 1];

            window.setTimeout(function() { callback(argumentsLength); }, 500);
        """
    }

    // Then I should get the expected length
    assertEquals(argumentsLength, 100L)
}

Functions

call

open fun call(vararg args: Any, async: Boolean = false, script: () -> String): Any?

Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.

execute

abstract fun execute(vararg args: Any, async: Boolean = false, script: () -> String): Any?

Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.

get

open operator fun get(value: String): Any?

Get the value of a global-JavaScript variable.

invoke

open operator fun invoke(vararg args: Any, async: Boolean = false, script: () -> String): Any?

Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.

run

open fun run(vararg args: Any, async: Boolean = false, script: () -> String): Any?

Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.

set

open operator fun set(name: String, value: Any?): Unit

Set the value of a global-JavaScript variable.