Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - prompt cause 'document is not focused'

Tags:

javascript

If I add a prompt to the function it works once, but gives the error:

"Uncaught (in promise) DOMException: Document is not focused" at the second attempt.

This is the code:

function site(str) {
  var url = prompt();
  var text = 'The URL is ';
  (async() => {
    await navigator.clipboard.writeText(text + url);
  })();
}
<button class="button" onclick='site()'>URL</button>

I've asked my best friend, Google, but I can't find any solutions. What am I doing wrong?

like image 984
geirilja Avatar asked Jan 01 '26 06:01

geirilja


2 Answers

It is probably caused by this bug in chromium (Issue #1085949) which makes your prompt call take focus from the Document and not return it when closed. I was not able to reproduce this issue on Safari and Firefox.

The same bug can be reproduced by doing alert instead of prompt followed by navigator.clipboard.writeText.

like image 84
Alexander Suraphel Avatar answered Jan 03 '26 11:01

Alexander Suraphel


Your JS may be running on a child page. The following works for me:

await parent.navigator.clipboard.writeText('text to copy to Clipboard here.');
like image 44
Leo PHAM Avatar answered Jan 03 '26 12:01

Leo PHAM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!