1

Assume that we through JavaScript have added a method to the global/window object called logToken, that we want to run from the developer console. It's function should be to log a token (string) and copy it to the clipboard. The code exists within a React project and is thus compiled with webpack. How could we achieve this?

We can't use navigator.clipboard.writeText because we get the error "Uncaught (in promise) DOMException: Document is not focused", as the focus is in the developer console.

We can't use copy() because it's only defined in the developer console, not in your JavaScript. It will copy the token to the clipboard, but it will also throw a compilation error upon page load.

Is there any other way around this?

window.logToken = () => {
  const token = 'my magic token';
  
  console.log(token);

  copy(dmdpToken); // works but throws an error on page load
  navigator.clipboard.writeText(token); // doesn't work and throws error
}
Amsvartner
  • 733
  • 7
  • 19
  • But why does it matter if `copy()` is only available in devtools, you want to run it from there anyway? – Reyno Feb 22 '22 at 10:50
  • Use the deprecated document.execCommand: [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/q/400212) – wOxxOm Feb 22 '22 at 10:54
  • Using `copy` triggers a compile error, edited the question to clarify. – Amsvartner Feb 22 '22 at 12:03

0 Answers0