Document is not defined on chrome mv3 in a background.ts file

Hello, I have created a context menu that copies something to your clipboard. This is the function I'm using:
function copyToClipboard(text: string) {
const el = document.createElement("textarea")
el.value = text
document.body.appendChild(el)
el.select()
document.execCommand("copy")
document.body.removeChild(el)
}
function copyToClipboard(text: string) {
const el = document.createElement("textarea")
el.value = text
document.body.appendChild(el)
el.select()
document.execCommand("copy")
document.body.removeChild(el)
}
This works fine with firefox but not on chrome. So, is there a better way to add a string to the users clipboard via a context menu listener event that works with chrome mv3?
43 Replies
lab
lab•16mo ago
with chrome mv3, you will want to send some event to a content script on that page or spawning an offscreen document. BGSW does not have access to document
jonah
jonah•16mo ago
Ah that makes sense, do you have an example of spawning an offscreen document by any chance?
Arcane
Arcane•16mo ago
@j0ner has reached level 2. GG!
lab
lab•16mo ago
There's an issue on github with some workaround: https://github.com/PlasmoHQ/plasmo/issues/527
GitHub
[RFC] Support for Offscreen Documents · Issue #527 · PlasmoHQ/plasmo
How do you envision this feature/change to look/work like? The Offscreen API has been added since Chrome 109 version. This solves a problem with the service worker which can't access the DOM or...
lab
lab•16mo ago
Tho note that the offscreen docs is not the target webpage itself
jonah
jonah•16mo ago
i see, thank you for the help mv3 was a mistake 😭
lab
lab•16mo ago
lol it might but it's also pretty powerful once you get a hang of it it's like going from single threaded programming to multi-threaded
jonah
jonah•16mo ago
isnt there a bunch of stuff not supported yet via mv3 and bugs
lab
lab•16mo ago
the concept of mutex/arc doesn't exist in syncronous programming not supported in the way it worked in mv2 yeah it's the same as sync code cannot run in async runtime xD...
jonah
jonah•16mo ago
true i guess the roll-out was just a total mess on chrome
lab
lab•16mo ago
it's just incompatible in its nature, so you will have to figure out alternative yeah that's... their issue xD
jonah
jonah•16mo ago
thank god firefox hasnt switched yet
lab
lab•16mo ago
idk I wish firefox would just participate and improve the specs
jonah
jonah•16mo ago
have they not been trying to add mv3 to firefox?
lab
lab•16mo ago
the background page is easy to work with but architecture-wise, it's a vector for malicious process not really, in ff there's no BGSW, it's still background page
Want results from more Discord servers?
Add your server