I'm working on an extension that takes takes a snapshot of a visible part of the page and copies it to the clipboard. I decided to use the new Clipboard API to do that. The code that handles the capture and copy is located in the background.js of my extension. Here's what it the relevant part looks like:
chrome.tabs.captureVisibleTab(function(dataUrl) {
convertToBlob(dataUrl).then((data) => {
navigator.clipboard.write([
new ClipboardItem({
'image/png': data
})
]);
});
});
This action is triggered by a click on a widget that I inject into the page using chrome.tabs.executeScript
. I'm working in Chrome only. However, every time I try it, I get this error:
Uncaught (in promise) DOMException: Document is not focused.
Initially, I assumed that the document I was capturing was not in focus, however it doesn't seem to be the case. My document.hasFocus()
was returning true. Then I thought that for some reason which I can't fathom it wants the background.html to be focused. So I ended up creating a custom background.html that contains an input field and prior to performing the navigator.clipboard access, I would focus and click on that input programmatically. No dice. EDIT: I performed an actual page check and the background.html is indeed not focused, even though I dispatched the focus to it, which make sense. What doesn't make sense is why this is happening since I'm supposed to capture stuff to clipboard in any context with this API.
I did run a navigator.permissions query to see if clipboard-write access was granted, and it was.
At this point I'm out of ideas, does anyone have any recommendations? Thank you! Luka