HTML id with javascript to trigger a write to clipboard

37 Views Asked by At

When I run this script (embedded in a HTML page) 'GG' isn't copied to the clipboard. Can someone help/explain why and assist me in getting it working? Thanks.

document.getElementById("blah3");
let s ="GG";
navigator.clipboard.writeText(s);
1

There are 1 best solutions below

5
Chris Hamilton On

Like the link in the comments says, you need to attach a clipboard write to a user action for security reasons. Usually you make a user click a button and add an event listener for it.

function writeToClipboard() {
  navigator.clipboard.writeText('GG');
}

document.querySelector('#my-button').addEventListener('click', writeToClipboard)

DISCLAIMER: THE FOLLOWING IS FOR EDUCATIONAL PURPOSES. PLEASE DO NOT TRY TO DODGE SECURITY FEATURES.

If you really want to shimmy around security you can do some questionable things.

You could keep trying to write until the user does something and it succeeds. Using a timeout will prevent the thread from blocking. Best to wait a few ms before polling again so as not to make the CPU go brrr

function tryToWrite() {
    navigator.clipboard.writeText('GG').catch(() => setTimeout(tryToWrite, 50));
}

tryToWrite();

or you could attach it to events that are likely to happen

let wrote = false;

function writeToClipboard() {
  if (wrote) return;
  navigator.clipboard.writeText('GG').then(() => wrote = true);
}

window.addEventListener('focus', writeToClipboard, {once: true});
window.addEventListener('mousedown', writeToClipboard, {once: true});
window.addEventListener('keydown', writeToClipboard, {once: true});

You'll always be restricted to the user interacting with the page in some way before you can write.