gpt4 book ai didi

javascript - 如何在后台运行 Chrome 扩展程序的情况下捕获网页上的复制事件?

转载 作者:行者123 更新时间:2023-12-03 02:26:31 25 4
gpt4 key购买 nike

我已经尝试了几个小时来寻找 Chrome 扩展程序能够监听常规网站上的复制事件的解决方案。到目前为止,我最接近的解决方案是在创建此事件脚本时:

function onCopy(e) {
console.log("onCopy works"); //it doesn't :(
chrome.runtime.sendMessage({event: "copy"});
}

chrome.runtime.sendMessage('copy', onCopy, true);

oncopy.js 中的函数应该向 popup.js 中类似的函数发送消息:

chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.event == "copy") {
console.log("copy detected");
}
sendResponse({});
});

不幸的是,console.log("onCopy Works") 创建的消息是唯一有效的。如果有人能澄清我做错了什么以及我没有做什么,我真的很感激。这里的目标是每次用户复制事件时从剪贴板获取数据。这是我的 manifest.json 的相关部分,以防有帮助:

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

最佳答案

如果您的消息处理程序位于 popup.js 中,并且它实际上是 popup.html 中的脚本,那么它仅在打开弹出窗口时才起作用。
即使它在后台页面 - 它也不会显示警报。您应该使用 console.log 并在 DevTools 中打开后台页面来查看结果。
您还需要chrome.runtime.onMessage.addListenerchrome.runtime.sendMessage在内容脚本和弹出/背景页面之间发送和接收消息:

// in background pagage or in popup page (works only when popup is opened)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("received: " + request);
sendResponse("message has been processed by background page");
});

// in content script injected into website page
document.addEventListener("copy", () =>
chrome.runtime.sendMessage(
{ event: "click" },
msg => console.log(msg)))

关于javascript - 如何在后台运行 Chrome 扩展程序的情况下捕获网页上的复制事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com