'Copy to clipboard in chrome extension V3

I am developing a chrome extension V3. I want to copy content to clipboard in my JS file.
The manifest.json as below,

    "background" :{
        "service_worker" :"eventPage.js"
    },
    "permissions" : [
        "contextMenus",
        "clipboardWrite"      
    ]

I have try 2 solution for copy feature.

Solution 1:

    const el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
  

The result:

Error in event handler: ReferenceError: document is not defined at copyToClipboard 

Solution 2:

navigator.clipboard.writeText(str);

The result:

Error in event handler: TypeError: Cannot read properties of undefined (reading 'writeText')

The chrome extension is run as a service worker. So it seems I can't access DOM document and have no grant of writeText. Does anyone have another suggestion?

Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source