Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

244
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda