Copy to clipboard with Vaadin button in FireFox

Viewed 145

Here is the code for the Vaadin button:

String textToCopy = "COPY ME!!!";
Button copyBtn = new Button("");
copyBtn.setButtonLayout(false, new IconSelf(VaadinIcon.COPY_O), "Copy"));
copyBtn.addClickListener(event -> {
          getUI().get().getPage().executeJs("navigator.clipboard.writeText(`" + textToCopy + "`);");
    Notification.show(getTranslation(PAGESTRING + "attributestoclipboard"))
});

To copy my custom text I used navigator.clipboard.writeText(...).
Works in Chrome and Edge but not in Firefox.
Firefox also blocked document.execCommand("copy") when i used it in the executeJS(...) function.

I think i need to add a onClick function to the button. How can i do this with Vaadin?

1 Answers
copyBtn.getElement().executeJs("this.addEventListener('click', e => navigator.clipboard.writeText($0))", textToCopy);

Note that it's strongly discouraged to use string concatenation to dynamically build strings that are passed to executeJs because of the risk of cross-site scripting vulnerabilities. That's why my suggestion also uses $0 to reference the separately passed string. This is similar to using prepared statements with SQL.

Related