Kotlin DOM API compatibility library providing JavaScript interoperability and DOM manipulation utilities
—
Modern networking capabilities including Fetch API for HTTP requests, XMLHttpRequest for legacy support, headers manipulation, and comprehensive CORS handling for web applications.
Modern promise-based HTTP request API with comprehensive feature support.
/**
* Make HTTP requests using the Fetch API
*/
external fun fetch(input: dynamic, init: RequestInit = definedExternally): Promise<Response>
/**
* HTTP Request representation
*/
external class Request(input: dynamic, init: RequestInit = definedExternally) : Body {
/** The request method */
val method: String
/** The request URL */
val url: String
/** The request headers */
val headers: Headers
/** The request type */
val type: RequestType
/** The request destination */
val destination: RequestDestination
/** The request referrer */
val referrer: String
/** The request referrer policy */
val referrerPolicy: String
/** The request mode */
val mode: RequestMode
/** The request credentials mode */
val credentials: RequestCredentials
/** The request cache mode */
val cache: RequestCache
/** The request redirect mode */
val redirect: RequestRedirect
/** The request integrity */
val integrity: String
/** Whether to keep the connection alive */
val keepalive: Boolean
/** Clone the request */
fun clone(): Request
}
/**
* HTTP Response representation
*/
external class Response(body: dynamic = definedExternally, init: ResponseInit = definedExternally) : Body {
/** The response type */
val type: ResponseType
/** The response URL */
val url: String
/** Whether the response was redirected */
val redirected: Boolean
/** The response status code */
val status: Short
/** Whether the response is successful (200-299) */
val ok: Boolean
/** The response status text */
val statusText: String
/** The response headers */
val headers: Headers
/** The response trailer */
val trailer: Promise<Headers>
/** Clone the response */
fun clone(): Response
companion object {
/** Create error response */
fun error(): Response
/** Create redirect response */
fun redirect(url: String, status: Short = definedExternally): Response
}
}
/**
* Request/Response body interface
*/
external interface Body {
/** Whether the body has been used */
val bodyUsed: Boolean
/** The body as a ReadableStream */
val body: ReadableStream<Uint8Array>?
/** Read body as ArrayBuffer */
fun arrayBuffer(): Promise<ArrayBuffer>
/** Read body as Blob */
fun blob(): Promise<Blob>
/** Read body as FormData */
fun formData(): Promise<FormData>
/** Read body as JSON */
fun json(): Promise<Any?>
/** Read body as text */
fun text(): Promise<String>
}
/**
* HTTP Headers manipulation
*/
external class Headers(init: dynamic = definedExternally) {
/** Append header value */
fun append(name: String, value: String)
/** Delete header */
fun delete(name: String)
/** Get header value */
fun get(name: String): String?
/** Check if header exists */
fun has(name: String): Boolean
/** Set header value */
fun set(name: String, value: String)
/** Get header keys */
fun keys(): Iterator<String>
/** Get header values */
fun values(): Iterator<String>
/** Get header entries */
fun entries(): Iterator<Array<String>>
/** Iterate over headers */
fun forEach(callback: (String, String, Headers) -> Unit, thisArg: Any = definedExternally)
}Request initialization and configuration options.
/**
* Request initialization options
*/
external interface RequestInit {
/** HTTP method */
var method: String?
/** Request headers */
var headers: dynamic
/** Request body */
var body: dynamic
/** Request referrer */
var referrer: String?
/** Referrer policy */
var referrerPolicy: String?
/** Request mode (cors, no-cors, same-origin) */
var mode: RequestMode?
/** Credentials mode */
var credentials: RequestCredentials?
/** Cache mode */
var cache: RequestCache?
/** Redirect mode */
var redirect: RequestRedirect?
/** Subresource integrity */
var integrity: String?
/** Keep connection alive */
var keepalive: Boolean?
/** Associated window */
var window: Any?
}
/**
* Response initialization options
*/
external interface ResponseInit {
/** Status code */
var status: Short?
/** Status text */
var statusText: String?
/** Response headers */
var headers: dynamic
}
/**
* Request types
*/
enum class RequestType {
EMPTY,
AUDIO,
FONT,
IMAGE,
SCRIPT,
STYLE,
TRACK,
VIDEO
}
/**
* Request destinations
*/
enum class RequestDestination {
DOCUMENT,
EMBED,
FONT,
IMAGE,
MANIFEST,
MEDIA,
OBJECT,
REPORT,
SCRIPT,
SERVICEWORKER,
SHAREDWORKER,
STYLE,
TRACK,
VIDEO,
WORKER,
XSLT
}
/**
* Request modes
*/
enum class RequestMode {
NAVIGATE,
SAME_ORIGIN,
NO_CORS,
CORS
}
/**
* Request credentials modes
*/
enum class RequestCredentials {
OMIT,
SAME_ORIGIN,
INCLUDE
}
/**
* Request cache modes
*/
enum class RequestCache {
DEFAULT,
NO_STORE,
RELOAD,
NO_CACHE,
FORCE_CACHE,
ONLY_IF_CACHED
}
/**
* Request redirect modes
*/
enum class RequestRedirect {
FOLLOW,
ERROR,
MANUAL
}
/**
* Response types
*/
enum class ResponseType {
BASIC,
CORS,
DEFAULT,
ERROR,
OPAQUE,
OPAQUEREDIRECT
}Legacy HTTP request API with comprehensive feature support.
/**
* XMLHttpRequest for HTTP requests
*/
external class XMLHttpRequest : XMLHttpRequestEventTarget {
/** The request ready state */
val readyState: Short
/** Request timeout in milliseconds */
var timeout: Int
/** Whether to send credentials with cross-origin requests */
var withCredentials: Boolean
/** Upload object for monitoring upload progress */
val upload: XMLHttpRequestUpload
/** The response URL */
val responseURL: String
/** The response status */
val status: Short
/** The response status text */
val statusText: String
/** The response type */
var responseType: XMLHttpRequestResponseType
/** The response body */
val response: Any?
/** The response as text */
val responseText: String
/** The response as XML document */
val responseXML: Document?
/** Open a request */
fun open(method: String, url: String, async: Boolean = definedExternally, user: String? = definedExternally, password: String? = definedExternally)
/** Set request header */
fun setRequestHeader(name: String, value: String)
/** Send the request */
fun send(body: dynamic = definedExternally)
/** Abort the request */
fun abort()
/** Get response header */
fun getResponseHeader(name: String): String?
/** Get all response headers */
fun getAllResponseHeaders(): String
/** Override MIME type */
fun overrideMimeType(mime: String)
companion object {
const val UNSENT: Short = 0
const val OPENED: Short = 1
const val HEADERS_RECEIVED: Short = 2
const val LOADING: Short = 3
const val DONE: Short = 4
}
}
/**
* Base class for XMLHttpRequest event targets
*/
external interface XMLHttpRequestEventTarget : EventTarget {
/** Load start event */
var onloadstart: ((ProgressEvent) -> Unit)?
/** Progress event */
var onprogress: ((ProgressEvent) -> Unit)?
/** Abort event */
var onabort: ((ProgressEvent) -> Unit)?
/** Error event */
var onerror: ((ProgressEvent) -> Unit)?
/** Load event */
var onload: ((ProgressEvent) -> Unit)?
/** Timeout event */
var ontimeout: ((ProgressEvent) -> Unit)?
/** Load end event */
var onloadend: ((ProgressEvent) -> Unit)?
}
/**
* XMLHttpRequest upload monitoring
*/
external interface XMLHttpRequestUpload : XMLHttpRequestEventTarget
/**
* Progress event for upload/download monitoring
*/
external class ProgressEvent(type: String, eventInitDict: ProgressEventInit = definedExternally) : Event {
/** Whether length is computable */
val lengthComputable: Boolean
/** Bytes loaded */
val loaded: Double
/** Total bytes */
val total: Double
}
external interface ProgressEventInit : EventInit {
var lengthComputable: Boolean?
var loaded: Double?
var total: Double?
}
/**
* XMLHttpRequest response types
*/
enum class XMLHttpRequestResponseType {
EMPTY,
ARRAYBUFFER,
BLOB,
DOCUMENT,
JSON,
TEXT
}Form data handling for HTTP requests.
/**
* Form data for HTTP requests
*/
external class FormData(form: HTMLFormElement = definedExternally) {
/** Append form field */
fun append(name: String, value: String)
/** Append file field */
fun append(name: String, blobValue: Blob, filename: String = definedExternally)
/** Delete form field */
fun delete(name: String)
/** Get form field value */
fun get(name: String): dynamic
/** Get all values for form field */
fun getAll(name: String): Array<dynamic>
/** Check if form field exists */
fun has(name: String): Boolean
/** Set form field value */
fun set(name: String, value: String)
/** Set file field value */
fun set(name: String, blobValue: Blob, filename: String = definedExternally)
/** Get form field keys */
fun keys(): Iterator<String>
/** Get form field values */
fun values(): Iterator<dynamic>
/** Get form field entries */
fun entries(): Iterator<Array<dynamic>>
/** Iterate over form fields */
fun forEach(callback: (dynamic, String, FormData) -> Unit, thisArg: Any = definedExternally)
}URL parsing and manipulation utilities.
/**
* URL parsing and manipulation
*/
external class URL(url: String, base: String = definedExternally) {
/** The complete URL */
var href: String
/** The URL origin */
val origin: String
/** The URL protocol */
var protocol: String
/** The URL username */
var username: String
/** The URL password */
var password: String
/** The URL host (hostname:port) */
var host: String
/** The URL hostname */
var hostname: String
/** The URL port */
var port: String
/** The URL pathname */
var pathname: String
/** The URL search string */
var search: String
/** The URL search parameters */
val searchParams: URLSearchParams
/** The URL hash */
var hash: String
companion object {
/** Convert domain to ASCII */
fun domainToASCII(domain: String): String
/** Convert domain to Unicode */
fun domainToUnicode(domain: String): String
/** Create object URL */
fun createObjectURL(obj: dynamic): String
/** Revoke object URL */
fun revokeObjectURL(url: String)
}
}
/**
* URL search parameters manipulation
*/
external class URLSearchParams(init: dynamic = definedExternally) {
/** Append parameter */
fun append(name: String, value: String)
/** Delete parameter */
fun delete(name: String)
/** Get parameter value */
fun get(name: String): String?
/** Get all values for parameter */
fun getAll(name: String): Array<String>
/** Check if parameter exists */
fun has(name: String): Boolean
/** Set parameter value */
fun set(name: String, value: String)
/** Sort parameters */
fun sort()
/** Get parameter keys */
fun keys(): Iterator<String>
/** Get parameter values */
fun values(): Iterator<String>
/** Get parameter entries */
fun entries(): Iterator<Array<String>>
/** Iterate over parameters */
fun forEach(callback: (String, String, URLSearchParams) -> Unit, thisArg: Any = definedExternally)
/** Convert to string */
override fun toString(): String
}Usage Examples:
import kotlinx.browser.window
import org.w3c.fetch.*
import org.w3c.xhr.*
// Basic fetch request
suspend fun fetchData(): String {
val response = fetch("/api/data").await()
if (!response.ok) {
throw Exception("HTTP ${response.status}: ${response.statusText}")
}
return response.text().await()
}
// POST request with JSON
suspend fun postJson(data: Any) {
val response = fetch("/api/submit", object : RequestInit {
override var method = "POST"
override var headers = mapOf(
"Content-Type" to "application/json",
"Accept" to "application/json"
)
override var body = JSON.stringify(data)
}).await()
if (!response.ok) {
throw Exception("Failed to submit data")
}
}
// File upload with FormData
suspend fun uploadFile(file: File) {
val formData = FormData()
formData.append("file", file)
formData.append("description", "Uploaded file")
val response = fetch("/api/upload", object : RequestInit {
override var method = "POST"
override var body = formData
}).await()
val result = response.json().await()
console.log("Upload result:", result)
}
// XMLHttpRequest with progress monitoring
fun downloadWithProgress(url: String, onProgress: (Double) -> Unit) {
val xhr = XMLHttpRequest()
xhr.onprogress = { event ->
if (event.lengthComputable) {
val progress = event.loaded / event.total
onProgress(progress)
}
}
xhr.onload = {
console.log("Download complete")
}
xhr.onerror = {
console.error("Download failed")
}
xhr.open("GET", url)
xhr.send()
}
// Headers manipulation
val headers = Headers()
headers.set("Authorization", "Bearer token123")
headers.set("Content-Type", "application/json")
headers.append("Accept", "application/json")
headers.forEach { value, name, _ ->
console.log("$name: $value")
}
// URL manipulation
val url = URL("https://example.com/search?q=kotlin")
url.searchParams.set("lang", "en")
url.searchParams.append("filter", "recent")
console.log(url.toString()) // https://example.com/search?q=kotlin&lang=en&filter=recent
// Custom headers and CORS
suspend fun apiCall() {
val response = fetch("/api/data", object : RequestInit {
override var mode = RequestMode.CORS
override var credentials = RequestCredentials.INCLUDE
override var headers = mapOf(
"X-Custom-Header" to "value",
"Accept" to "application/json"
)
}).await()
val data = response.json().await()
console.log("API response:", data)
}Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-dom-api-compat