2

i have a question, i have a code, which is partially working.

let dataName = "String"
navigator.clipboard
        .writeText(dataName) //push string into clipboard
        .then(() => {
          alert(dataName + "successfully copied");
          closeWindow()
          })
      .catch(() => {
        alert("something went wrong");
          });

In this version, the code is pushing dataName into the clipboard and gives an alert, after that it closes it. If i delete the alert, it closes the window, without copying it into the clipboard, not going into the catch ("something went wrong"). I do not want to have the alert, it should just push the string into the clipboard and closes it. Note: Code is embedded into a HTML, which is empty, except of the script. Code is partially from: How do I copy to the clipboard in JavaScript?

  • By the way: Code in the sense of a program's source code (not some numerical code, etc.) is an uncountable noun like milk. You don't have _a_ code, you just have code, or a piece of code, or some code. Getting this right will make you instantly sound more professional. – CherryDT Sep 20 '22 at 08:37

1 Answers1

0

If you add a parameter to the catch and log what you receive you will get following error DOMException: Document is not focused. So the user needs to have the document focused for this to work, i.e. try running navigator.clipboard.writeText("text")in the console. Below code should work, but stackoverflow is preventing this to work and gives a error

DOMException: The Clipboard API has been blocked because of a permissions policy applied to the current document. See error link for more details.

const copy = () => {
navigator.clipboard
  .writeText("some text") //push string into clipboard
  .then((e) => {
    alert(e + "successfully copied");
    closeWindow()
  })
  .catch((e) => {
    console.log(e)
  });
}
<button onClick="copy()">Click me</button>
PEPEGA
  • 2,214
  • 20
  • 37