Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
e49c10e
perf: opt-in lookups run by the page instead of reading the whole doc…
nathanfallet Nov 19, 2026
d4208ba
fix: in-page lookups survive a navigation and release what they no lo…
nathanfallet Nov 19, 2026
e734a54
fix: all-or-nothing in-page results, best-effort release, frames thro…
nathanfallet Nov 19, 2026
bdbe3aa
fix: a closed target is an error, and the array is released on every …
nathanfallet Nov 19, 2026
8c1d102
fix: release the array of an in-page lookup on cancellation too
nathanfallet Nov 19, 2026
ed8b3f7
perf: page-wide lookups always run in the page, without a setting
nathanfallet Nov 20, 2026
1aa78f6
test: wait for the frame before comparing two document reads, enable …
nathanfallet Nov 20, 2026
c5e5813
docs: lookups run by the page leave the DOM agent disabled
nathanfallet Nov 20, 2026
d01b383
fix: selectAll leaves no object in the page and reads the document wh…
nathanfallet Nov 20, 2026
3be39c8
fix: in-page lookups leave no object in the page, and bound their cle…
nathanfallet Nov 20, 2026
4207cc1
feat: elements found in the page fill their node ids, tree and parent…
nathanfallet Nov 20, 2026
c863042
test: set the node of a found element through DefaultElement
nathanfallet Nov 20, 2026
80e26dd
fix: bind a found element only to an identical document node, and rel…
nathanfallet Nov 20, 2026
52c3be6
docs: node ids of a found element may be 0 until it is bound
nathanfallet Nov 20, 2026
5297b13
test: compare lookups on a page that finished loading
nathanfallet Nov 20, 2026
c7316cc
Merge remote-tracking branch 'origin/main' into perf/lookups-in-page
nathanfallet Nov 21, 2026
1b94158
refactor: split the lookup code to pass the detekt checks
nathanfallet Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ to heavy tools like Selenium or Puppeteer — all without relying on WebDriver.
* **No external dependencies** – kdriver interacts directly with the browser using WebSockets and JSON — no need for
Chromium wrappers or native libraries.
* **Session and cookie management** – Start with a clean profile every time or load/save cookies between runs.
* **Remote browsers** – Attach to a browser behind a reverse proxy; CSS lookups run in the page and never transfer the
whole document (see [how lookups work](docs/home/quickstart.md#how-lookups-work)).
* **Element utilities** – Coming soon: intuitive APIs to query, interact with, and wait for DOM elements.

## Motivation
Expand Down
85 changes: 30 additions & 55 deletions core/src/commonMain/kotlin/dev/kdriver/core/dom/DefaultElement.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,28 @@ import kotlin.random.Random
*/
open class DefaultElement(
val tab: Tab,
override var node: DOM.Node,
override var tree: DOM.Node? = null,
node: DOM.Node,
tree: DOM.Node? = null,
) : Element {

private val logger = KtorSimpleLogger("Element")

private val binding = ElementBinding(node, tree)

/**
* The node of this element. For an element found in the page (no [tree]), the first read after the document was
* read, while the page has not changed since, takes the document's node of the same backend node id, with its node
* ids and parent id, as a lookup on the document gave it, when it holds the same subtree (see [ElementBinding]).
*/
override var node: DOM.Node
get() = binding.bindFrom((tab as? DefaultTab)?.keptDocument()).node
set(value) = binding.replaceNode(value)

/** The document this element was read from: for an element found in the page, filled as [node] is. */
override var tree: DOM.Node?
get() = binding.bindFrom((tab as? DefaultTab)?.keptDocument()).tree
set(value) = binding.replaceTree(value)

private var remoteObject: Runtime.RemoteObject? = null

// The node the cached [remoteObject] was resolved for: [rawApply] reuses the object only while [node] is still
Expand Down Expand Up @@ -90,6 +106,17 @@ open class DefaultElement(
override val attrs: List<String>
get() = node.attributes?.chunked(2)?.map { it.first() } ?: emptyList()

/**
* Binds an element found in the page (no node id, no [tree]) to the whole document, as [update] does, without
* resolving its object again: [node] becomes the document's node of the same backend node id, with its node ids,
* and [tree] the document. Used before a lookup under this element, which queries it by node id.
*/
internal suspend fun bindToDocument() {
val doc = currentDocument()
doc.filterRecurse { it.backendNodeId == node.backendNodeId }?.let { node = it }
tree = doc
}

override suspend fun updateRemoteObject(): Runtime.RemoteObject? {
val resolvedFor = backendNodeId
remoteObject = tab.dom.resolveNode(backendNodeId = resolvedFor).`object`
Expand Down Expand Up @@ -158,59 +185,7 @@ open class DefaultElement(
private suspend fun getStableCoordinates(): CoordinateResult? {
return try {
apply<CoordinateResult?>(
jsFunction = """
function() {
if (!this || !this.isConnected) return null;

return new Promise(resolve => {
let lastTop = null;
let lastLeft = null;
let stableFrames = 0;
const maxAttempts = 10;
let attempts = 0;

const checkStable = () => {
attempts++;
const rect = this.getBoundingClientRect();

if (rect.width === 0 || rect.height === 0) {
resolve(null);
return;
}

if (lastTop !== null &&
Math.abs(rect.top - lastTop) < 1 &&
Math.abs(rect.left - lastLeft) < 1) {
stableFrames++;
if (stableFrames >= 2) {
resolve({
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
});
return;
}
} else {
stableFrames = 0;
}

lastTop = rect.top;
lastLeft = rect.left;

if (attempts < maxAttempts) {
requestAnimationFrame(checkStable);
} else {
// Timeout: use current position
resolve({
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
});
}
};

requestAnimationFrame(checkStable);
});
}
""".trimIndent(),
jsFunction = STABLE_COORDINATES_JS,
awaitPromise = true
)
} catch (e: EvaluateException) {
Expand Down
52 changes: 52 additions & 0 deletions core/src/commonMain/kotlin/dev/kdriver/core/dom/ElementBinding.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package dev.kdriver.core.dom

import dev.kdriver.cdp.domain.DOM
import dev.kdriver.core.tab.DefaultTab

/**
* The node and the document of a [DefaultElement], and the binding of an element found in the page to the document
* [DefaultTab] keeps from its last read, when it still matches the page, without any command: node ids, [tree] and
* parent are then those a lookup on the document gave. The document's node is taken only when it holds the same
* subtree as the one found (ids aside), so a read never changes what the element shows. Each kept document is looked
* at once; without one, the element stays as found until `update` or a lookup under it.
*/
internal class ElementBinding(node: DOM.Node, tree: DOM.Node?) {

var node: DOM.Node = node
private set

var tree: DOM.Node? = tree
private set

// The epoch of the kept document the last binding attempt looked at.
private var checkedAt: Long = NOT_CHECKED

fun replaceNode(value: DOM.Node) {
node = value
checkedAt = NOT_CHECKED
}

fun replaceTree(value: DOM.Node?) {
tree = value
checkedAt = NOT_CHECKED
}

/** Binds to [kept] when this element has no tree yet and [kept] was not looked at; returns this binding. */
fun bindFrom(kept: DefaultTab.DocumentSnapshot?): ElementBinding {
if (tree == null && kept != null && kept.epoch != checkedAt) {
checkedAt = kept.epoch
val found = node
val documentNode = kept.nodeOf(found.backendNodeId)
if (documentNode != null && documentNode.withoutIds() == found.withoutIds()) {
tree = kept.root
node = documentNode
}
}
return this
}

private companion object {
// No kept document looked at yet: epochs are never negative.
const val NOT_CHECKED = -1L
}
}
15 changes: 15 additions & 0 deletions core/src/commonMain/kotlin/dev/kdriver/core/dom/Extensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,18 @@ val Input.MouseButton.buttonsMask: Int
Input.MouseButton.FORWARD -> 16
Input.MouseButton.NONE -> 0
}

/**
* This node and its subtree without their node ids and parent ids: two reads of the same unchanged nodes, one by
* `DOM.describeNode` and one by `DOM.getDocument`, are then equal.
*/
internal fun DOM.Node.withoutIds(): DOM.Node = copy(
nodeId = 0,
parentId = null,
children = children?.map { it.withoutIds() },
contentDocument = contentDocument?.withoutIds(),
shadowRoots = shadowRoots?.map { it.withoutIds() },
pseudoElements = pseudoElements?.map { it.withoutIds() },
templateContent = templateContent?.withoutIds(),
importedDocument = importedDocument?.withoutIds(),
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package dev.kdriver.core.dom

/**
* The function [DefaultElement] applies to an element to read its coordinates once its position is stable across
* several frames; it resolves null when the element is detached or has no size.
*/
internal val STABLE_COORDINATES_JS = """
function() {
if (!this || !this.isConnected) return null;

return new Promise(resolve => {
let lastTop = null;
let lastLeft = null;
let stableFrames = 0;
const maxAttempts = 10;
let attempts = 0;

const checkStable = () => {
attempts++;
const rect = this.getBoundingClientRect();

if (rect.width === 0 || rect.height === 0) {
resolve(null);
return;
}

if (lastTop !== null &&
Math.abs(rect.top - lastTop) < 1 &&
Math.abs(rect.left - lastLeft) < 1) {
stableFrames++;
if (stableFrames >= 2) {
resolve({
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
});
return;
}
} else {
stableFrames = 0;
}

lastTop = rect.top;
lastLeft = rect.left;

if (attempts < maxAttempts) {
requestAnimationFrame(checkStable);
} else {
// Timeout: use current position
resolve({
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
});
}
};

requestAnimationFrame(checkStable);
});
}
""".trimIndent()
Loading
Loading