I wanted to create very small extension for website that will automatically copy some value to the clipboard.
The problem is that I want it to copy the value even if browser is not focused e.g.:
I tried to use Clipboard API:
navigator.clipboard.writeText(...)
but I don't think it will work because browser have to be focused(I think).
When page is focused then copying works fine. If I try to switch to different application I get an exception when my extension tries to copy the value:
DOMException: Document is not focused.
Is there any way to do this?
This is not possible for security reasons.. It's hard to imagine anyone wanting this behavior...
This document has a lot of good info..
In Chrome, you can request clipboard-write
permissions to write to clipboard outside of a small user generated event, although it does not appear as though Chrome limits you to when you can write to clipboard.. According to the article below, you can write to the clipboard in Chrome from the background, etc.. See the note at the bottom of this section for more info.
If Chrome does allow you to write to clipboard from the background or if the window is not selected, you could possibly use the Page Visiblity API to kick off the copy event when "that" specific window is not visible.
You could possibly even use the window.addEventListener('blur', function(){...})
handler to test, etc...
All in all, this MAY be possible in Chrome, but it is definitely not supported in Firefox.
You can check out the differences between browsers and how they handle clipboard related events/permissions/etc, here..