ContentScript.js与Chrome扩展程序之间的通信

时间:2012-05-02 15:13:58

标签: google-chrome google-chrome-extension

我只是想将当前标签页面发送到我的扩展程序:

以下是我的manifest.json

{
 "name": "DocUrlExtention",
 "version": "1.0",
 "manifest_version": 2,
 "description": "The first extension that I made.",
 "browser_action": {
 "default_icon": "icon.png",
 "default_popup": "popup.html"
},
 "content_scripts": [
 {
  "matches": ["http://*/*"],
  "js": ["contentscript.js"]
 }
 ]}

以下是我的contentscript.js

chrome.extension.sendRequest({url: window.location.href}, function(response) {
   console.log(response.farewell);
});

以下是我的popup.html

<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>

<script>
    chrome.extension.onRequest.addListener(
      function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "from a content script:" + sender.tab.url :
                    "from the extension");
      });
</script>

<!-- JavaScript and HTML must be in separate files for security. -->
<!--<script src="popup.js"></script>-->
</head>
<body>
<div id="mydiv">Doc Id:</div>
</body>
</html>

我在控制台中看不到任何内容。我是Chrome扩展新用户。

1 个答案:

答案 0 :(得分:1)

您的清单文件包含"manifest_version": 2,,可启用Content Security Policy。默认情况下,Inline JavaScript will not be executed。而且,有no way to relax the CSP such that inline JavaScript is allowed

你有两个选择:

  1. 删除"manifest_version": 2(禁用默认CSP)。
  2. 将内联JavaScript移动到外部文件。
  3. 建议使用第二种方法,并在代码中建议

    ...
    <!-- JavaScript and HTML must be in separate files for security. -->
    <!--<script src="popup.js"></script>-->
    </head>
    ...
    

    PS。弹出窗口的开发工具可以通过浏览器操作图标上的右键单击打开,然后选择最后一个选项"Inspect popup"