CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-js

Kotlin Standard Library for JavaScript target with comprehensive W3C DOM bindings and JavaScript interoperability features.

Pending
Overview
Eval results
Files

browser-integration.mddocs/

Browser Integration

IMPORTANT: The browser APIs in kotlin.browser package are deprecated since Kotlin 1.4 and will be removed in future versions. For modern browser integration, use the kotlinx.browser library instead.

This documentation describes the deprecated browser APIs that are still present in kotlin-stdlib-js for compatibility.

Capabilities

Deprecated Browser Global Objects

⚠️ DEPRECATED: These APIs are deprecated since Kotlin 1.4. Use kotlinx.browser instead.

/**
 * Browser window object
 * @deprecated Use kotlinx.browser.window instead
 */
@Deprecated("Use kotlinx.browser.window instead", ReplaceWith("window", "kotlinx.browser.window"))
external val window: Window

/**
 * HTML document object
 * @deprecated Use kotlinx.browser.document instead
 */
@Deprecated("Use kotlinx.browser.document instead", ReplaceWith("document", "kotlinx.browser.document"))
external val document: Document

/**
 * Local storage for persistent data
 * @deprecated Use kotlinx.browser.localStorage instead
 */
@Deprecated("Use kotlinx.browser.localStorage instead", ReplaceWith("localStorage", "kotlinx.browser.localStorage"))
external val localStorage: Storage

/**
 * Session storage for temporary data
 * @deprecated Use kotlinx.browser.sessionStorage instead
 */
@Deprecated("Use kotlinx.browser.sessionStorage instead", ReplaceWith("sessionStorage", "kotlinx.browser.sessionStorage"))
external val sessionStorage: Storage

Usage Examples:

import kotlinx.browser.*

// Access browser globals
console.log("Page loaded!")
console.error("Error occurred")

// Document manipulation
val title = document.title
document.title = "My Kotlin/JS App"

// Local storage
localStorage.setItem("user", "john_doe")  
val user = localStorage.getItem("user") // "john_doe"
localStorage.removeItem("user")

// Session storage (cleared when tab closes)
sessionStorage.setItem("temp_data", "some_value")
val tempData = sessionStorage.getItem("temp_data")

// Window operations
window.alert("Hello from Kotlin!")
val width = window.innerWidth
val height = window.innerHeight

// Navigation
location.href = "https://example.com"
history.back()

DOM Element Creation Utilities

Convenient functions for creating and configuring DOM elements.

/**
 * Create HTML element with initialization block
 */
fun Document.createElement(name: String, init: Element.() -> Unit): Element

/**
 * Create specific HTML elements with type safety
 */
fun Document.createDiv(init: HTMLDivElement.() -> Unit = {}): HTMLDivElement
fun Document.createSpan(init: HTMLSpanElement.() -> Unit = {}): HTMLSpanElement  
fun Document.createInput(init: HTMLInputElement.() -> Unit = {}): HTMLInputElement
fun Document.createButton(init: HTMLButtonElement.() -> Unit = {}): HTMLButtonElement
fun Document.createImg(init: HTMLImageElement.() -> Unit = {}): HTMLImageElement
fun Document.createA(init: HTMLAnchorElement.() -> Unit = {}): HTMLAnchorElement

/**
 * Append newly created element to parent
 */
fun Element.appendElement(name: String, init: Element.() -> Unit): Element

/**
 * Append text node to element
 */
fun Element.appendText(text: String): Text

Usage Examples:

import kotlinx.browser.*
import kotlinx.dom.*
import org.w3c.dom.*

// Create elements with initialization
val div = document.createElement("div") {
    className = "container"
    id = "main-container"
    textContent = "Hello, World!"
}

// Type-safe element creation
val input = document.createInput {
    type = "text"
    placeholder = "Enter your name"
    value = "Default value"
}

val button = document.createButton {
    textContent = "Click me"
    onclick = { event ->
        console.log("Button clicked!")
    }
}

// Append to document
document.body?.appendChild(div)
document.body?.appendChild(input)
document.body?.appendChild(button)

// Chain element creation
val container = document.body?.appendElement("div") {
    className = "wrapper"
    
    appendElement("h1") {
        textContent = "Title"
    }
    
    appendElement("p") {
        appendText("This is a paragraph with ")
        appendElement("strong") {
            textContent = "bold text"
        }
        appendText(".")
    }
}

CSS Class Manipulation

Utilities for working with CSS classes on DOM elements.

/**
 * Check if element has CSS class
 */
fun Element.hasClass(cssClass: String): Boolean

/**
 * Add CSS classes to element
 */
fun Element.addClass(vararg cssClasses: String)

/**
 * Remove CSS classes from element
 */
fun Element.removeClass(vararg cssClasses: String)

/**
 * Toggle CSS class on element
 */
fun Element.toggleClass(cssClass: String)

/**
 * Set CSS classes (replaces all existing classes)
 */
fun Element.setClasses(vararg cssClasses: String)

Usage Examples:

import kotlinx.dom.*
import org.w3c.dom.*

val element = document.getElementById("my-element")!!

// Check for class
val hasActive = element.hasClass("active") // true/false

// Add classes
element.addClass("highlight", "important")

// Remove classes  
element.removeClass("old-style", "deprecated")

// Toggle class (add if missing, remove if present)
element.toggleClass("expanded")

// Replace all classes
element.setClasses("new-style", "modern", "responsive")

// Conditional class management
if (someCondition) {
    element.addClass("special")
} else {
    element.removeClass("special")
}

DOM Tree Manipulation

Utilities for manipulating the DOM tree structure.

/**
 * Remove all child nodes from element
 */
fun Node.clear()

/**
 * Check if node is text node
 */
val Node.isText: Boolean

/**
 * Check if node is element node
 */
val Node.isElement: Boolean

/**
 * Get all child elements (excluding text nodes)
 */
val Element.childElements: List<Element>

/**
 * Find first child element with matching tag name
 */
fun Element.firstChildElement(tagName: String): Element?

/**
 * Remove element from its parent
 */
fun Element.remove()

Usage Examples:

import kotlinx.dom.*
import kotlinx.browser.*
import org.w3c.dom.*

val container = document.getElementById("container")!!

// Clear all content
container.clear()

// Check node types
val textNode = document.createTextNode("Hello")
val elementNode = document.createElement("div")

console.log("Text node: ${textNode.isText}") // true
console.log("Element node: ${elementNode.isElement}") // true

// Work with child elements
val parent = document.createElement("div") {
    appendElement("h1") { textContent = "Title" }
    appendText("Some text")
    appendElement("p") { textContent = "Paragraph" }
}

val elements = parent.childElements // List of h1 and p elements (no text)
val firstH1 = parent.firstChildElement("h1") 

// Remove element
val unwantedElement = document.getElementById("unwanted")
unwantedElement?.remove()

Storage Utilities

Enhanced utilities for working with browser storage.

/**
 * Storage interface (localStorage/sessionStorage)
 */
external interface Storage {
    val length: Int
    fun key(index: Int): String?
    fun getItem(keyName: String): String?
    fun setItem(keyName: String, keyValue: String)
    fun removeItem(keyName: String)
    fun clear()
}

/**
 * Type-safe storage operations
 */
fun Storage.getBoolean(key: String): Boolean?
fun Storage.setBoolean(key: String, value: Boolean)
fun Storage.getInt(key: String): Int?
fun Storage.setInt(key: String, value: Int)
fun Storage.getDouble(key: String): Double?
fun Storage.setDouble(key: String, value: Double)

/**
 * JSON storage operations
 */
inline fun <reified T> Storage.getObject(key: String): T?
inline fun <reified T> Storage.setObject(key: String, value: T)

Usage Examples:

import kotlinx.browser.*

// String storage
localStorage.setItem("username", "alice")
val username = localStorage.getItem("username") // "alice"

// Type-safe storage
localStorage.setBoolean("isLoggedIn", true)
val isLoggedIn = localStorage.getBoolean("isLoggedIn") // true

localStorage.setInt("score", 1500)
val score = localStorage.getInt("score") // 1500

// JSON object storage
data class UserPrefs(val theme: String, val notifications: Boolean)

val prefs = UserPrefs("dark", true)
localStorage.setObject("preferences", prefs)
val savedPrefs = localStorage.getObject<UserPrefs>("preferences")

// Storage management
val totalItems = localStorage.length
for (i in 0 until totalItems) {
    val key = localStorage.key(i)
    console.log("Key: $key")
}

localStorage.clear() // Remove all items

Types

// Browser global objects
external val window: Window
external val document: Document
external val localStorage: Storage
external val sessionStorage: Storage
external val console: Console
external val location: Location
external val history: History
external val navigator: Navigator

// Storage interface
external interface Storage {
    val length: Int
    fun key(index: Int): String?
    fun getItem(keyName: String): String?
    fun setItem(keyName: String, keyValue: String)
    fun removeItem(keyName: String)
    fun clear()
}

// Browser API interfaces
external interface Window : EventTarget
external interface Console {
    fun log(vararg data: Any?)
    fun error(vararg data: Any?)
    fun warn(vararg data: Any?)
    fun info(vararg data: Any?)
}

external interface Location {
    var href: String
    val hostname: String
    val pathname: String
    val search: String
    val hash: String
    fun reload()
}

external interface History {
    val length: Int
    fun back()
    fun forward()
    fun go(delta: Int)
    fun pushState(data: Any?, title: String, url: String?)
    fun replaceState(data: Any?, title: String, url: String?)
}

external interface Navigator {
    val userAgent: String
    val language: String
    val languages: Array<String>
    val cookieEnabled: Boolean
    val onLine: Boolean
}

// DOM utility extensions
val Node.isText: Boolean
val Node.isElement: Boolean
val Element.childElements: List<Element>

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-js

docs

browser-integration.md

collections.md

coroutines.md

index.md

io-encoding.md

javascript-interop.md

math-time.md

reflection.md

uuid.md

w3c-dom-apis.md

tile.json