Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - Google Chrome Extension - Script Injections

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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"]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...