javascript - Chrome 扩展程序 : sendResponse returning empty object

标签 javascript google-chrome-extension

我知道有很多类似的问题: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 = 未定义

我不明白我做错了什么。 我希望您能提供帮助,并且答案尚未在其他地方得到解释。

最佳答案

问题的实际原因是extension.onMessage是runtime.onMessage的一个已弃用的别名,因此您对同一事件有两个监听器,但只有第一个注册监听器的sendResponse会传输到调用者,即{ }.

也就是说,整个工作流程可以极其简化:不需要后台脚本或内容脚本,因此您可以从manifest.json 中删除“background”和“content_scripts”。也不需要消息传递。

您需要一个 browser_action 弹出窗口,只需在弹出脚本中读取剪贴板即可。

manifest.json:

{
  "manifest_version": 2,
  "name": "test",
  "version": "1.0",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions": [
    "clipboardRead"
  ]
}

popup.html:

<!DOCTYPE html>
<body>
  <p id=text contenteditable=true></p>
  <script src=popup.js></script>
</body>

popup.js:

document.getElementById('text').focus();
document.execCommand('paste');

这是扩展程序的全部内容。

关于javascript - Chrome 扩展程序 : sendResponse returning empty object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61075829/

相关文章:

javascript - react 生命周期与 react Hook useEffect

javascript - 如何在特定索引处将项目插入到数组中 (JavaScript)

javascript - chrome.tabs.Tab 未在 popup.js 脚本中定义

javascript - 在 Chrome 扩展中使用 sendMessage 时 webkitMediaStream 对象类型丢失

javascript - Chrome 扩展 : Cant appendchild in my popup file

javascript - 列出 Chrome 扩展程序中的所有网络可访问资源

javascript - 在没有服务器的情况下处理 POST 或 GET 请求

javascript - 悬停文本并显示 html 表格

javascript - Jquery 无法识别 <%=%> scriptlet 标记中的变量

javascript - AJAX 阻止了 chrome 扩展内容脚本