它适用于Chrome,但在Firefox Nightly 52.0a1中,点击通知后会出现此错误:
document.execCommand('cut'/'copy')被拒绝,因为它不是 从短暂运行的用户生成的事件处理程序内部调用
copyTextToClipboard()函数取自Copy to Clipboard in Chrome Extension
manifest.js
{
"description": "Test for JSON Notifiaction + Clipboard Copy",
"manifest_version": 2,
"name": "Test3",
"version": "1.0",
"permissions": [
"<all_urls>",
"clipboardWrite",
"notifications",
"webRequest"
],
"background": {
"scripts": ["background.js"]
}
}
background.js
'use strict';
let JSON_obj = {
"name" : "ABCDEFG",
"age" : 3,
};
function logURL(requestDetails) {
// filter rules to check requestDetails.url for specific parameters {
notify(JSON_obj);
// }
}
function notify(notifyMessage) {
var options = {
type: "basic",
iconUrl: chrome.extension.getURL("icons/test.png"),
title: "",
message: JSON.stringify(notifyMessage, null, "\t")
};
chrome.notifications.create("uniqueID3", options);
}
chrome.notifications.onClicked.addListener(function() {
console.log('Clicked notification message text: ', JSON_obj);
copyTextToClipboard(JSON.stringify(JSON_obj, null, "\t"));
});
function copyTextToClipboard(copyText) {
var copyFrom = document.createElement("textarea");
copyFrom.textContent = copyText;
var body = document.getElementsByTagName('body')[0];
body.appendChild(copyFrom);
copyFrom.select();
document.execCommand('copy');
body.removeChild(copyFrom);
}
chrome.webRequest.onBeforeRequest.addListener(
logURL, {
urls: ["<all_urls>"]
}
);
答案 0 :(得分:0)
请参阅https://github.com/mdn/webextensions-examples/blob/master/context-menu-copy-link-with-types/clipboard-helper.js#L2 - 您无法从后台脚本进行复制。您的copyTextToClipboard代码在注入到示例中完成的页面时工作正常:https://github.com/mdn/webextensions-examples/blob/master/context-menu-copy-link-with-types/background.js#L31