List icon Contents

Clipboard

This guide describes how to use clipboard in JxBrowser.

Prerequisites

Clipboard works only in secure contexts and when the browser is focused.

Necessary permissions

When using navigator.clipboard object to access the clipboard, the browser requires permissions. By default, necessary permissions are denied. Here’s how to grant them:

Java
Kotlin
engine.permissions().set(RequestPermissionCallback.class, (params, tell) -> {
    PermissionType type = params.permissionType();
    if (type == PermissionType.CLIPBOARD_READ_WRITE) {
        tell.grant();
    } else if (type == PermissionType.CLIPBOARD_SANITIZED_WRITE) {
        tell.grant();
    } else {
        tell.deny();
    }
});
engine.permissions().set(
    RequestPermissionCallback::class.java,
    RequestPermissionCallback { params, tell ->
        val type = params.permissionType()
        when (type) {
            PermissionType.CLIPBOARD_READ_WRITE -> tell.grant()
            PermissionType.CLIPBOARD_SANITIZED_WRITE -> tell.grant()
            else -> tell.deny()
        }
    })

When writing to the clipboard results from a user interaction, such as a mouse click, the browser requires the CLIPBOARD_SANITIZED_WRITE permission. In other cases, the browser requires the CLIPBOARD_READ_WRITE permission.

Using document commands

Permissions listed above have no effect on document.execCommand('copy'). This command is disabled by default. To enable it, run the following code:

Java
Kotlin
browser.settings().allowJavaScriptAccessClipboard();
browser.mainFrame().ifPresent(frame -> {
    frame.executeJavaScript("document.execCommand('copy')");
});
browser.settings().allowJavaScriptAccessClipboard()
browser.mainFrame().ifPresent { frame ->
    frame.executeJavaScript<Boolean>("document.execCommand('copy')")
}

When executing the same command using JxBrowser API, no settings or permissions are required. To copy content using the document command, run:

Java
Kotlin
browser.mainFrame().ifPresent(frame -> {
    frame.execute(EditorCommand.copy());
});
browser.mainFrame().ifPresent { frame ->
    frame.execute(EditorCommand.copy())
}