Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

854
Views
Copy text to clipboard: Cannot read properties of undefined reading 'writeText'

I have a button

enter image description here

When I clicked on COPY

copyImageLinkText({ mouseenter, mouseleave }, e) {
  this.showCopiedText = !this.showCopiedText
  navigator.clipboard.writeText(this.imageLink)

  clearTimeout(this._timerId)
  mouseenter(e)
  this._timerId = setTimeout(() => mouseleave(e), 1000)
},

This line seems to work perfectly locally on my MacBook Pro

navigator.clipboard.writeText(this.imageLink)

It's not working when I build and deployed it to my dev server.

TypeError: Cannot read properties of undefined (reading 'writeText')

enter image description here

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The use of navigator.clipboard requires a secure origin. So if your dev environment is being served over HTTP, then the clipboard method won't be available.

According to MDN Clipboard docs: "This feature is available only in secure contexts (HTTPS)"

Maybe you could check if this method is available with window.isSecureContext, and disable the Copy Text button accordingly.


Workaround

The best option is to use HTTPS in your dev environment.

But since you asked for a workaround, here's a (very hacky) working sample. It uses the Document.exec command, which is being deprecated in favor of ClipboardAPI.

function unsecuredCopyToClipboard(text) {
  const textArea = document.createElement("textarea");
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    document.execCommand('copy');
  } catch (err) {
    console.error('Unable to copy to clipboard', err);
  }
  document.body.removeChild(textArea);
}

You could then use navigator.clipboard == undefined to use the fallback method, otherwise use the normal navigator.clipboard.writeText(...) function where supported.

about 4 years ago · Juan Pablo Isaza Report

0

It is better to use an async and put your code in try catch block.

async copyCode() {
 try {
     await navigator.clipboard.writeText(this.input);
 } catch (e) {
     console.log(e);
 }
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!