0

我很清楚有关于这个问题的旧问题,但我还没有从他们那里找到解决方案。

我的扩展程序应该检测 contentScript.js 中的复制事件并传递信息,该事件已被检测到 oncopy.js。之后,oncopy.js 应该复制用户剪贴板内容并将它们传递给 popup.js,其中内容使用 Google 的存储 API 存储,并设置为 popup.html 中的输入字段值。

复制检测工作完美,但我不知道之后该怎么做。这是我的第一个扩展,所以我仍在尝试掌握一些东西。

这是我的 manifest.jsons 相关部分:

"permissions": [
  "activeTab",
  "storage",
  "clipboardRead"
],

"background": {
  "scripts": ["oncopy.js"],
  "persistent": false
},

"content_scripts": [
  {
    "matches": ["http://*/*", "https://*/*"],
    "js": ["contentScript.js"]
  }
]

内容脚本.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>
4

0 回答 0