Communication between ContentScript.js and Chrome

2019-01-12 12:37发布

I simply want to send the current tab url to my extension:

Following is my 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"]
 }
 ]}

Following is my contentscript.js

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

Following is my 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>

I don't see anything in console. I am new to Chrome extensions.

1条回答
闹够了就滚
2楼-- · 2019-01-12 12:55

Your manifest file contains "manifest_version": 2,, which enables the Content Security Policy. By default, Inline JavaScript will not be executed. And, there is no way to relax the CSP such that inline JavaScript is allowed.

You've got two options:

  1. Remove "manifest_version": 2 (which disabled the default CSP).
  2. Move the inline JavaScript to an external file.

The second method is recommended, and also suggested in your code...

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

PS. The Dev tools for the pop-up can be opened by right-clicking on the browser action icon, and selecting the last option, "Inspect popup".

查看更多
登录 后发表回答