Rafael Nicola
Rafael Nicola

Reputation: 84

Simple navigator.clipboard.writeText() does not work

So I am using a MacBook and I have a copy button that copies a generated text input on a text field.

This is the code:

document.querySelector("#btnCopy").addEventListener('click', copy);
async function copy(){
    
    var text = document.querySelector("#docNumber");
    text.select();
    navigator.clipboard.writeText(text.value)
}

When I check the clipboard nothing has been copied.

Any suggestion of what is going on?

Thanks, community.

Upvotes: 2

Views: 8528

Answers (3)

ocodo
ocodo

Reputation: 30258

This may be caused by hosting via http instead of https. Although, in this case we can't be sure of the cause.

When a page is called over http on any address that isn't localhost or 127.0.0.1. The browser will leave navigator.clipboard as undefined.

Upvotes: 1

ℛɑƒæĿᴿᴹᴿ
ℛɑƒæĿᴿᴹᴿ

Reputation: 5336

The following approach works in Chrome, Firefox, Internet Explorer and Edge, and in recent versions of Safari (copy support was added in version 10 which was released Oct 2016).

document.querySelector("#btnCopy").addEventListener('click', copyToClipboard);

function copyToClipboard() {
  let text = document.querySelector("#docNumber");
  text.select();
  text = text.value;

  if (window.clipboardData && window.clipboardData.setData) {
    // IE: prevent textarea being shown while dialog is visible
    return window.clipboardData.setData("Text", text);

  } else if (document.queryCommandSupported && 
             document.queryCommandSupported("copy")) {
    var textarea = document.createElement("textarea");
    textarea.textContent = text;
    // Prevent scrolling to bottom of page in MS Edge
    textarea.style.position = "fixed";
    document.body.appendChild(textarea);
    textarea.select();
    try {
      // Security exception may be thrown by some browsers
      return document.execCommand("copy");
    } catch (ex) {
      console.warn("Copy to clipboard failed.", ex);
      return false;
    } finally {
      document.body.removeChild(textarea);
    }
  }
}
<input id="docNumber" type="text" value="Clipboard text test">
<button id="btnCopy">Copy to Clipboard</button>

Reference:

Upvotes: 2

polisen
polisen

Reputation: 327

I think you need to assign the selected text to something.

let t = text.select();

or better yet:

navigator.clipboard.writeText(text.select())

Upvotes: 1

Related Questions