内容脚本的Chrome扩展响应未定义

时间:2015-10-05 18:42:23

标签: javascript google-chrome google-chrome-extension content-script

我有一个简单的Chrome扩展程序,代码如下。单击弹出窗口中的按钮时,我想从用户浏览器选项卡中复制所选文本。

问题:我的内容脚本selection.js返回的所有响应都未找到

非常感谢任何帮助:)

的manifest.json

{
  "manifest_version": 2,

  "name": "Selected Text",
  "description": "copying your highlighted text",
  "version": "0.1",

  "browser_action": {
   "default_title": "Selected Text",
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "permissions": [
   "tabs",
   "<all_urls>"
   ],
   "content_scripts": [
    {
     "matches": ["<all_urls>"],
     "js": ["selection.js"],
     "run_at": "document_start",
     "all_frames": true
    }
   ]
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Selected Text</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Selected Text</h1>
    <p id="text">Not Selected</p>
    <button id="checkPage">Copy Highlighted Text!</button>
  </body>
</html>

popup.js

function getSelectedText() {
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response) {
      // PROBLEM: response is always undefined
      var text = response.data;
      document.getElementById("text").innerHTML = text;                                              
    });
  });                
};

document.addEventListener('DOMContentLoaded', function() {
  var checkPageButton = document.getElementById('checkPage');
  checkPageButton.addEventListener('click', function() {
    getSelectedText();
  }, false);
}, false);

selection.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.method == "getSelection")
    sendResponse({data: window.getSelection().toString()});
  else
    sendResponse({}); // snub them.
});

1 个答案:

答案 0 :(得分:1)

请记住在更改代码时要同时执行以下操作:

  1. 重新加载您的扩展程序(在chrome:// extensions页面中)
  2. 刷新您正在测试的网站页面(即Ctrl + R)
  3. 看起来内容脚本只会通过执行2)刷新,而弹出窗口会被刷新1)。