I have this simple setup where a user clicks on an element, then javascript uses a confirm( ) window to confirm the user really wants to copy the text to their clipboard. If they confirm positively, the text gets copied. Works perfectly in Safari and Firefox, but Chrome keeps giving me "Focus" errors.
Here's the most simple version, this works in all browsers including Chrome:
document.getElementById("copyip").addEventListener("click",function($event)
{
var $users_ip = document.getElementById("ip").innerHTML;
navigator.clipboard.writeText($users_ip);
});
^ that works just fine. Click text, text is copied. But it's a little too rude to do this without confirming with the user first. So this is the code I actually am trying to use:
document.getElementById("copyip").addEventListener("click",function($event)
{
var $users_ip = document.getElementById("ip").innerHTML;
if (window.confirm("Copy IP Address " + $users_ip + " to your clipboard?"))
{
navigator.clipboard.writeText($users_ip);
}
});
This code also works great in Firefox and Safari. But in Chrome, it gives me the following error:
Uncaught (in promise) DOMException: Document is not focused.
I'm not sure what that means. I always thought focus was for form elements, maybe links depending on your OS settings. But how can a document have or not have focus? And how do you give it focus? The browser is still the frontmost window after you hit confirm.
So I tried putting the clipboard writing command in a little 10ms timer, so it waits just a tiny bit before trying to copy. But that made no difference. I also tried using the .focus( ) function to give focus to the window, the document, the specific item being copied, right before the actual clipboard write happens. But it still gives the same error.
What is actually going on here? I feel like maybe I'm misunderstanding the error and thats why I'm barking up the wrong tree?