Home > Enterprise >  how to catch error for navigator.clipboard.writeText
how to catch error for navigator.clipboard.writeText

Time:08-11

navigator.clipboard.writeText

doesn't work on all browsers. I tried the following code. it works and copies on firefox but on opera, it shows the alert that the code is copied but actually, it doesn't copy the link and doesn't show the error prompt. and on the browser console, it shows this error: Uncaught (in promise) DOMException: Document is not focused.

so, how can I catch this error to show the link in prompt for the user to copy it manually?

if not possible, what is the most supported way to copy the current link to the clipboard?

let shareProjectBtn = document.getElementById("share-project-btn");
function copyCurrentURL() {

navigator.clipboard.writeText(window.location.href);
try {
  if (navigator.clipboard.value !== null) {
    alert("Project's link copied to clipboard");
}
} catch (error) {
  window.prompt("Your browser can't copy the link, please copy this link manually",window.location.href);
}
}

CodePudding user response:

You could use Promise.catch() to handle it. Here's an example grabbed straight from MDN:

navigator.clipboard.writeText("<empty clipboard>").then(() => {
  /* clipboard successfully set */
}, () => {
  /* clipboard write failed */
});

CodePudding user response:

navigator.clipboard.writeText returns a Promise, so you can either:

move it into your try block and use: await navigator.clipboard.writeText(window.location.href)

or use:

navigator.clipboard.writeText(window.location.href).catch((err) => window.prompt("Your browser can’t copy the link, …"))

You can read more about Promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

  • Related