Google Chrome Extension - Script Injections

2019-01-16 16:19发布

I'm trying to get my Chrome Extension to inject some javascript with content_scripts, using this previous answer as a reference.

manifest.json

"name": "My Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
    "matches": ["http://pagetoinject/script/into/*"],
    "js": ["contentscript.js"]
}]  

contenscript.js:

var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);

( also tried this method with no success. )

var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

I keep getting this javascript error. Here's a screenshot.

enter image description here GET chrome-extension://invalid/ (anonymous function)

3条回答
祖国的老花朵
2楼-- · 2019-01-16 16:27

In addition to the answers above I notice that in your contentscript.js you are just adding another script i.e script.js Why don't you directly add script.js through content_scripts in manifest.json.

查看更多
Luminary・发光体
3楼-- · 2019-01-16 16:31
  1. In your manifest file, "manifest_version": 2 is specified. This automatically activates a stricter mode, in which all extension's files are not available to web pages by default.
  2. Your original code would never work, because the <script> element is immediately removed after injection (the script file does not have a chance to load).

As a result of 1., the following error shows up in the console:

Failed to load resource                             chrome-extension://invalid/

To fix the problem, add script.js to the whitelist, "web_accessible_resources" in your manifest file:

{
  "name": "Chrome Extension",
  "version": "1.0",
  "manifest_version": 2,
  "content_scripts": [{
      "matches": ["http://pagetoinject/script/into/*"],
      "js": ["contentscript.js"]
  }],
  "web_accessible_resources": ["script.js"]
}
查看更多
祖国的老花朵
4楼-- · 2019-01-16 16:33

The problem here is that you are using manifest_version : 2. If you make that manifest-version: 1 you'll not have any problems. Version 2 restricts many such features to improve security. Refer Google Content Security Policy for more details on the restrictions imposed in manifest version 2. I could not find your specific case mentioned in the CSP but when I changed the manifest version to 1 and executed your code it is working fine.

查看更多
登录 后发表回答