0

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);
theduck
  • 2,589
  • 13
  • 17
  • 23
Marcin K
  • 37
  • 5
  • 4
    You should make your question self-standing (i.e. include the relevant code for `copyToClipboard`). – junvar Nov 05 '19 at 15:09

1 Answers1

2

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>
junvar
  • 11,151
  • 2
  • 30
  • 46
  • When I run code snippet it outputs: "Failed to copy because: {}" When I run this on my page I get: "TypeError: "'name' member of PermissionDescriptor 'clipboard-write' is not a valid value for enumeration PermissionName" – Marcin K Nov 06 '19 at 12:54
  • 1
    OK, this Async Clipboard API is shipped to Chrome, wont work in Firefox – Marcin K Nov 06 '19 at 13:01
  • Exploring this my dang self. Seems that there is more work to do on the browser side for this Clipboard API. NS we can even request users to activate this from FF. Nevertheless, we can make this work using LocalStorage. It's kind of what a clipboard literally is. – CodeFinity May 23 '22 at 13:10