Clipboard copy

Is there a way, when clicking on a context item, to copy some text to the clipboard?

Hi Tatu, how are you ?

Wouldn’t it be ideal to update the tutorial ? with the new copy ?

window.copyToClipboard = async (str) => {
if (navigator.clipboard && navigator.clipboard.writeText) {
    try {
      await navigator.clipboard.writeText(str);
      console.log(“Copied!”);
      return;
    } catch (err) {
      console.warn("Failed xxx: ”, err);
    }
  }
}

You are correct that it uses on old API which is not supported by all browsers. So a bit related to this Clipboard API · Issue #17703 · vaadin/flow · GitHub, i.e. Asynchronous Clipboard API should be now supported by all browsers. And that means that we could potentially add utility API in Flow now and deprecate this older JavaScript workarounds.

1 Like

There is also an addon in the directory, that might help: Clipboard for Flow - Vaadin Add-on Directory

2 Likes

I save it like this to clipboard

 Button buttonCopy= new Button("Copy Data", VaadinIcon.COPY.create());
        buttonCopyOrderData.addClickListener(buttonClickEvent -> {
            UI.getCurrent().getPage().executeJs("navigator.clipboard.writeText($0)", textField.getValue());
        });
2 Likes

For me, this add-on works on Android but not iPhone. If it doesn’t work on iPhone it’s a no-go.

Based on Nico M solution…

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;

import java.util.function.Supplier;

public class CopyToClipboard extends Icon {

    public CopyToClipboard(Supplier<String> text) {
        setIcon(VaadinIcon.COPY);
        addClickListener(event -> {
            UI.getCurrent().getPage().executeJs("navigator.clipboard.writeText($0)", text.get());
        });
    }
}

Usage (e.g. with Vaadin TextField):

CopyToClipboard copyToClipBoard = new CopyToClipboard(() -> textField.getValue())

Vaadin 25.2 has fully working support for reading and writing to the clipboard, see How to use the Clipboard API in Vaadin or https://clipboard-cases.fly.dev/

woaaa,

Amazing thanks you…