Yokan / rebuild
Course 1 8624561

BrowserDownload.kt

composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/system/BrowserDownload.kt

implementation35 lines
1package eu.friedcutlet.yokan.services.system23import kotlin.io.encoding.Base644import kotlin.io.encoding.ExperimentalEncodingApi56/**7 * Hands [bytes] to the browser's download UI via a `Blob` object URL and a8 * synthetic anchor click. Bytes cross the JS boundary base64-encoded because9 * wasm `js()` parameters are limited to primitive/String types.10 */11@OptIn(ExperimentalEncodingApi::class)12internal fun triggerBrowserDownload(bytes: ByteArray, fileName: String, mimeType: String): Boolean =13    runCatching { triggerBrowserDownloadJs(Base64.encode(bytes), fileName, mimeType) }.isSuccess1415@OptIn(kotlin.js.ExperimentalWasmJsInterop::class)16private fun triggerBrowserDownloadJs(base64: String, fileName: String, mimeType: String) {17    js(18        """19        {20            const binary = atob(base64);21            const bytes = new Uint8Array(binary.length);22            for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);23            const blob = new Blob([bytes], { type: mimeType });24            const url = URL.createObjectURL(blob);25            const anchor = document.createElement('a');26            anchor.href = url;27            anchor.download = fileName;28            document.body.appendChild(anchor);29            anchor.click();30            anchor.remove();31            URL.revokeObjectURL(url);32        }33        """,34    )35}36

Search chapters, reference and source filenames.