【发布时间】:2020-04-07 08:29:37
【问题描述】:
我知道有很多类似的问题:Chrome extension messaging: sendResponse returning empty object 等,但我在提问之前阅读并尝试了所有这些问题。 我的问题有点不同,所以我认为这就是他们的解决方案对我不起作用的原因。
我想检测用户的Ctrl+C,所以当他点击扩展图标时,剪贴板的内容会显示在弹出窗口中。
这是我所做的: manifest.json 的一部分:
"permissions": [
"activeTab", "tabs", "<all_urls>", "clipboardRead"
],
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["oncopy.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
oncopy.js(内容脚本)
//https://stackoverflow.com/questions/2870369/google-chrome-extensions-how-to-detect-copy-action-ctrl-c-and-edit-copy
function onCopy(e) {
chrome.extension.sendMessage({event: "copy"});
}
document.addEventListener('copy',onCopy,true);
background.js(后台脚本):
var clipboardContents;
// This part of the script receive the 'copy' event.
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.event == "copy") {
// #### GET CLIPBOARD CONTENT #################################################
bg = chrome.extension.getBackgroundPage(); // get the background page
bg.document.body.innerHTML= ""; // clear the background page
// add a DIV, contentEditable=true, to accept the paste action
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;
// focus the helper div's content
helperdiv.innerHTML=""; // clear the buffer
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();
// trigger the paste action
bg.document.execCommand("Paste");
clipboardContents = helperdiv.innerText;
// ############################################################################
}
sendResponse({});
});
function send_response(callback){
callback(clipboardContents);
}
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
// When we get a message from the popup
send_response(function(clipboardContents) {
sendResponse(clipboardContents.toString());
});
return true;
// I also tried sendResponse() only, wih and without the return true;
// I also tried sendResponse(clipboardContents) only and sendResponse({data: clipboardContents});
});
popup.js:
chrome.runtime.sendMessage('popup_opened',function(response){
document.getElementById('text').innerHTML = response;
// I tried response.data
});
我总是得到:
响应 = 一个空对象
response.toString() = "[对象:对象]"
response.data = 未定义
我不明白我做错了什么。 我希望您能提供帮助,并且答案尚未在其他地方解释。
【问题讨论】:
标签: javascript google-chrome-extension