Can't get document.execCommand("copy") to work

I’m trying to use the document.execCommand(“copy”) method to get text onto the clipboard but it doesn’t work. The item is selected OK but never makes it to the clipboard. I got the code from a Stack Exchange answer:

// Create a dummy input to copy the string array inside it
  var dummy = document.createElement("input");

  // Add it to the document

  // Set its ID
  dummy.setAttribute("id", "dummy_id");

  // Output the array into it

  // Select it;

  // Copy its contents

  // Remove it as its not needed anymore

I am using exactly the same code, except that I swapped out “chkbox” for a variable containing the textContent of an Anki field. If I put a timeout on the last line I can see that the input field does appear, that it contains the right text and that the text is selected - but the actual copying never happens.

Anyone know where the problem might be? I tried using a textarea instead of an input but it didn’t help.

Actually Anki has to do something very similar at one point: anki/TagEditor.svelte at 16fe18d033a8c80ec5f06a70455b99fa72f33821 · ankitects/anki · GitHub
You could check if that works for you.

It seems the main difference is that it uses textarea instead of input. (don’t forget to remove Typescript type annotations).

1 Like

Thanks. Substituting that exact code gives an error unless I put “document.” in front of “execCommand”. With that change the error goes away but the field still isn’t copied (actually it did work a couple of times in maybe 7 attempts, but so did an earlier version of the Stack Exchange code - I can’t get it to work consistently).

Should I be putting something other than “document.” in front of “execCommand”?

Otherwise, could it be to do with the variable type of content (in textarea.value=content)? I have tried content = String.raw{{Anki field}} and content = document.getElementById(“Id”).textContent.

If it only works sometimes, it seems to be some timing issue. Something else is stealing keyboard focus before the function is executed.

Thanks a lot - yes that does seem to be the problem. If I kill AutoHotkey it generally works, but still not every time, and anyway I need AHK running (in fact the whole reason I’m copying the data to the clipboard is to get it into AHK).

I can’t find a way of getting the script to wait until the window has focus. I tried adding textarea.addEventListener(“focus”, copyFunction), and that sort of works, but you have to click in the textarea to get the copy operation to execute. Is there a better way to delay it until the window has focus?