Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda