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:
engine.permissions().set(RequestPermissionCallback.class, (params, tell) -> {
var type = params.permissionType();
if (type == PermissionType.CLIPBOARD_READ_WRITE
|| type == PermissionType.CLIPBOARD_SANITIZED_WRITE) {
tell.grant();
} else {
tell.deny();
}
});
engine.permissions.register(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:
browser.settings().allowJavaScriptAccessClipboard();
browser.mainFrame().ifPresent(frame -> {
frame.executeJavaScript("document.execCommand('copy')");
});
browser.settings.canJavaScriptAccessClipboard = true
browser.mainFrame?.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:
browser.mainFrame().ifPresent(frame -> {
frame.execute(EditorCommand.copy());
});
browser.mainFrame?.execute(EditorCommand.copy())