nor*_*ing 7 javascript copy-paste google-chrome-extension
我正在开发一个 chrome 扩展 V3。我想将 JS 文件中的内容复制到剪贴板。
Manifest.json 如下,
"background" :{
"service_worker" :"eventPage.js"
},
"permissions" : [
"contextMenus",
"clipboardWrite"
]
Run Code Online (Sandbox Code Playgroud)
我尝试了 2 个复制功能的解决方案。
解决方案一:
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);
Run Code Online (Sandbox Code Playgroud)
结果:
Error in event handler: ReferenceError: document is not defined at copyToClipboard
Run Code Online (Sandbox Code Playgroud)
解决方案2:
navigator.clipboard.writeText(str);
Run Code Online (Sandbox Code Playgroud)
结果:
Error in event handler: TypeError: Cannot read properties of undefined (reading 'writeText')
Run Code Online (Sandbox Code Playgroud)
Chrome 扩展作为 Service Worker 运行。所以看来我无法访问 DOM 文档并且没有授予 writeText 权限。还有人有其他建议吗?
谢谢。
小智 13
我将遵循 wOxxOm 给您的出色建议,并通过具体示例对其进行详细说明。您想要做的是让 ContentScript.js 在任何带有网页的活动选项卡上运行,因为您无法从 backGround.js 访问 DOM,然后向此脚本发送消息,您可以从其中复制到剪贴板。
清单.json
"background" :{
"service_worker" :"eventPage.js"
},
"permissions" : [
"contextMenus",
"clipboardWrite"
],
"content_scripts": [ // this is what you need to add
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
Run Code Online (Sandbox Code Playgroud)
从background.js,您将发送一条消息,该消息将在ContentScript.js中处理
背景.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id,
{
message: "copyText",
textToCopy: "some text"
}, function(response) {})
})
Run Code Online (Sandbox Code Playgroud)
在 contentScript.js 中,您将捕获消息并将其复制到剪贴板。
内容.js
chrome.runtime.onMessage.addListener( // this is the message listener
function(request, sender, sendResponse) {
if (request.message === "copyText")
copyToTheClipboard(request.textToCopy);
}
);
async function copyToTheClipboard(textToCopy){
const el = document.createElement('textarea');
el.value = textToCopy;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8311 次 |
| 最近记录: |