Marcin K
Marcin K

Reputation: 37

How to copy to clipboard javascript

My rep is too low to comment on original thread. https://stackoverflow.com/a/39643244/10651767

When I use function copyToClipboard(val) where val is taken from localstorage all I get in the clipboard is string "val" and not the value of val variable.

val= localStorage.getItem("val");
copyToClipboard(val);

Upvotes: 0

Views: 451

Answers (1)

junvar
junvar

Reputation: 11604

There's now a clipboard API you should use instead of creating dom elements and calling execCommand, which no longer seem to work but I haven't investigated to be certain.

document.querySelector('button').addEventListener('click', () => {
  let copyText = 'Random ' + Math.random();
  navigator.permissions.query({name: "clipboard-write"})
    .then(result => result.state == "granted" || result.state == "prompt")
    .then(() => navigator.clipboard.writeText(copyText))
    .then(() => console.log('Copied:', copyText))
    .catch(e => console.log('Failed to copy because:', e));
});
<button>Copy random text</button>

Upvotes: 2

Related Questions