我很清楚这个问题存在较早的问题,但我还没有找到解决方案。
我的扩展程序应该检测contentScript.js中的复制事件,并将检测到该事件的信息传递给oncopy.js。之后oncopy.js应该复制用户剪贴板内容并将它们传递给popup.js,其中内容使用Googles存储API存储,并设置为popup.html中的输入字段值。
复制检测工作完美,但我不知道在此之后该怎么做。这是我的第一次扩展,所以我仍然试图解决问题。
以下是我的manifest.jsons相关部分:
"permissions": [
"activeTab",
"storage",
"clipboardRead"
],
"background": {
"scripts": ["oncopy.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["contentScript.js"]
}
]
contentScript.js:
// Fires when copy event is detected
document.addEventListener("copy", () => {
chrome.runtime.sendMessage({event: "copy"}, msg => console.log(msg))
})
oncopy.js,例如后台脚本:
console.log("oncopy.js background scipt is running...");
// When copy event is detected and message of it is received, this starts to run
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
chrome.runtime.sendMessage({ event: "new clipboard" }, () => {
// This is supposed to get the clipboard contents from user
bg = chrome.extension.getBackgroundPage();
bg.document.body.innerHTML = "";
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();
bg.document.execCommand("Paste");
var clipboardContents = helperdiv.innerHTML;
});
sendResponse("Message has been processed by background page");
});
popup.js:
// This is supposed to set all of the clipboards to input fields values
document.body.onload = () => {
chrome.storage.sync.get("clipboards", (clipboards) => {
if (!chrome.runtime.error) {
document.getElementById("clipboard1").value = clipboards[0];
}
});
};
// The function that gets clipboard contents in oncopy.js is supposed to pass the contents here
// addClipboard is supposed to handle multiple clipboards, but for the sake of simplicity I'm using one as an example
function addClipboard(clipboard) {
chrome.storage.get("clipboards", (clipboards) => {
clipboards[0] = clipboard;
chrome.storage.sync.set({'clipboards': clipboards}, () => {
message('Clipboard saved');
});
document.getElementById("clipboard1").value = clipboards[0];
});
}
最后是popup.html:
<h2>Clipboards</h2>
<form>
<input type="text" id="clipboard1" value="Empty" readonly>
</form>