Reputation: 37
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
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