DominoKit simple copy to clipboard

Originally posted on 2020-10-27

Need to copy something to the clipboard? This static method will do it all. No need for any additional libraries and you can copy any text you want, even if it isn't on the screen.

import elemental2.dom.ClipboardEvent;
import elemental2.dom.DomGlobal;
import elemental2.dom.EventListener;
import jsinterop.base.Js;
import org.dominokit.domino.ui.notifications.Notification;
import org.dominokit.domino.ui.utils.DominoDom;

public class CopyToClipboard {
    public static void copyThis(String toCopy) {
        EventListener copyListener = e -> {
            ClipboardEvent clipboardEvent = Js.uncheckedCast(e);
            clipboardEvent.clipboardData.setData("text/plain", toCopy);
        DomGlobal.document.addEventListener("copy", copyListener);
        DomGlobal.document.removeEventListener("copy", copyListener);
        Notification.createInfo("Copied to clipboard").show();

You can add it to a button or something like this:

Button.create("Copy something")
      .addClickListener(evt -> CopyToClipboard.copyThis("testing123"));