Class ClipboardApi
This class wraps the browser's navigator.clipboard API, enabling server-side code to read from and write to the system clipboard. Reading from the clipboard is asynchronous and dispatches events to the requesting element.
Methods:
writeText(String)- Write text to clipboardreadText(Element)- Read text from clipboard (async, dispatches event)
Usage:
public class CopyPage extends HtmlPage implements ClipboardListener {
private TextInput input;
private Div output;
@Override
protected void createBody(Body body) {
input = new TextInput();
body.addElement(input);
Button copyBtn = new Button("Copy");
copyBtn.registerListener((MouseClickedEvent e) -> {
ClipboardApi.writeText(input.getValue());
}, MouseClickedEvent.class);
body.addElement(copyBtn);
Button pasteBtn = new Button("Paste");
pasteBtn.registerListener(this, ClipboardReadEvent.class);
pasteBtn.registerListener(this, ClipboardErrorEvent.class);
pasteBtn.registerListener((MouseClickedEvent e) -> {
ClipboardApi.readText(pasteBtn);
}, MouseClickedEvent.class);
body.addElement(pasteBtn);
output = new Div();
body.addElement(output);
}
@Override
public void onEvent(ClipboardReadEvent event) {
output.setText("Pasted: " + event.getText());
}
@Override
public void onEvent(ClipboardErrorEvent event) {
output.setText("Error: " + event.getMessage());
}
}
Browser Support:
The Clipboard API requires a secure context (HTTPS) and user permission. Browsers will prompt the user for permission before allowing clipboard access.
- Author:
- Marvin P. Warble Jr.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic voidReads text from the clipboard using the current page context.static voidReads text from the clipboard.static voidWrites text to the clipboard.static voidWrites text to the clipboard using the current page context.
-
Constructor Details
-
ClipboardApi
public ClipboardApi()
-
-
Method Details
-
writeText
Writes text to the clipboard using the current page context.This operation is synchronous from the server's perspective - the text is sent to the client and written to the clipboard. No event is dispatched on success.
- Parameters:
text- The text to write to the clipboard.
-
writeText
Writes text to the clipboard.- Parameters:
page- The page context.text- The text to write to the clipboard.
-
readText
Reads text from the clipboard using the current page context.This is an asynchronous operation. When the text is read, a
ClipboardReadEventis dispatched to the element. If an error occurs (e.g., permission denied), aClipboardErrorEventis dispatched instead.- Parameters:
element- The element that will receive the clipboard read event.
-
readText
Reads text from the clipboard.- Parameters:
page- The page context.element- The element that will receive the clipboard read event.
-