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

246
Views
Can I emulate/provoke failure to copy to clipboard from JS in Chrome?

I have a web page with some JavaScript code that copies stuff to the clipboard similar to what this demo does: https://davidwalsh.name/demo/javascript-copy-clipboard.php

My code is something like this:

// Within a listener that is triggered by a click on some button:
var copiedText = "...something";

navigator.clipboard.writeText(copiedText).then(
            function() {
                console.log("Succesfully copied");
            },
            function() {
                console.log("FAILED to copy!!!!!!");
            }
);

This works fine, but it always succeeds. I need to test that the behavior is correct when copying fails for whatever reason.

How can I cause the copy to fail on purpose so that I can test the behavior of my code in that situation?

I never get a prompt asking me permission to write to the clipboard.

In Chrome, I have tried going to the site settings for the site, and under "Clipboard" selecting "Block", but it does nothing (I guess that's only for reading from the clipboard).

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

0

Sure, just provide an invalid argument which will throw an exception during the stringification algorithm:

Note that this demo will work in your own page, but the success case won't work in the Stack Overflow code snippet iframe sandbox (where there is no clipboard permission).

function copyThenLog (input) {
  navigator.clipboard.writeText(input).then(
    () => console.log({success: true}),
    (ex) => {
      console.log({success: false});
      console.error(ex);
    },
  );
}

document.querySelector('.success').addEventListener('click', () => {
  const input = 'hello world';
  copyThenLog(input);
});

document.querySelector('.fail').addEventListener('click', () => {
  const input = {
    toString () {
      throw new Error('Oops');
    }
  };

  copyThenLog(input);
});
<div class="success">Click me to succeed</div>
<div class="fail">Click me to fail</div>

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!