Chrome扩展程序:sendResponse返回空对象

时间:2020-04-07 08:29:37

标签: 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
    });

我总是得到:
响应=一个Empy对象
response.toString()=“ [对象:对象]”
response.data =未定义

我不明白我在做什么错。 希望您能提供帮助,答案在其他地方也没有解释。

1 个答案:

答案 0 :(得分:1)

问题的实际原因是extension.onMessage是runtime.onMessage的不赞成使用的别名,因此您有两个针对同一事件的侦听器,但是只有第一个注册的侦听器的sendResponse被传送给调用者,即{{1} }。

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

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

manifest.json:

{}

popup.html:

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

popup.js:

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

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

相关问题