Google Chrome扩展程序 - 脚本注入 [英] Google Chrome Extension - Script Injections
问题描述
我试图让我的Chrome扩展程序使用 content_scripts 注入一些javascript。 stackoverflow.com/questions/9263671/google-chome-application-shortcut-how-to-auto-load-javascript/9310273#9310273 \">answer 作为参考。
manifest.json
I'm trying to get my Chrome Extension to inject some javascript with content_scripts
, using this previous answer as a reference.
"name": "My Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
"matches": ["http://pagetoinject/script/into/*"],
"js": ["contentscript.js"]
}]
contenscript.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);
我不断收到此javascript错误。以下是屏幕截图。
I keep getting this javascript error. Here's a screenshot.
< img src =https://i.stack.imgur.com/PTLMQ.pngalt =
GET chrome-extension:// invalid /
(匿名函数)
推荐答案
- 指定了
manifest_version:2
。这会自动激活一个更严格的模式,默认情况下,所有扩展的文件都不可用于网页。 原始代码不会工作,因为< script> ;
- 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. - 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).
在注入后立即删除元素(脚本文件没有机会加载)作为1.的结果,在控制台中显示以下错误:
As a result of 1., the following error shows up in the console:
Failed to load resource chrome-extension://invalid/
要解决此问题,请添加 script.js
加入白名单, web_accessible_resources
在您的清单文件
中:
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"]
}
这篇关于Google Chrome扩展程序 - 脚本注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!