[英]Copying to Clipboard in a content Script
有人可以解釋我如何寫到剪貼板嗎? 我已經看到了很多方法,但我似乎無法理解如何。 當前使用 manifest v3 並且沒有 background.js 腳本。
popup.js (action: download)<\/code> ->
contentscript.js (see below)<\/code>
function listener(info) {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (!request.action) return sendResponse({
err: 'Error: No Request Action'
});
switch (request.action) {
case "copy":
var textCopy = info.links.join(', ').replace(/"/g, '') // Text to Copy (String)
navigator.clipboard.writeText(textCopy).then(() => {
sendResponse('success')
}, () => {
sendResponse('failed')
});
break;
// Other Requests
}
}
);
}
至少在清單 v2 中,此方法有效。
首先,您需要將權限clipboardWrite
添加到清單中:
...
"permissions": ["clipboardWrite", ... ],
...
然后做類似這里回答的事情: https ://stackoverflow.com/a/18455088
這個想法是創建一個臨時文本區域來放置文本,然后允許您使用.select()
選擇其中的所有文本,然后使用document.execCommand('copy')
復制它。
感謝@cactus12 的幫助,這是對我有用的代碼!
var textCopy = '' // Text to Copy
var copyFrom = document.createElement("textarea");
copyFrom.textContent = `${textCopy}`;
document.body.appendChild(copyFrom);
copyFrom.select();
document.execCommand(`copy`);
copyFrom.blur();
document.body.removeChild(copyFrom);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.