Javascript - prompt cause 'document is not focused'

Viewed 4654

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?

3 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.

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.);

The same error will occur, if you don't await AND immediately after the command e.g. do an alert for feedback to the user, as the alert will steal the focus. Or if you otherwise navigate away or change the focus as a side effect.

(not the case in the above question, but just in case someone else stumbles across this problem and finds this question, I'll leave it here)

Related