jen*_*ush 8 javascript external-script google-chrome-extension
我无法在我的chrome扩展程序中加载和执行外部js-script.看起来和这个问题一样,但我仍然无法弄清楚为什么它在我的情况下不起作用.
我的想法是,我希望在我的内容脚本中有一些默认函数,它应该解析网页内容.对于某些特定的网页,我想加载和使用特定的解析器,所以我尝试为wep页面加载正确的js-script,这个脚本应该扩展默认解析器的功能.
到现在为止我只尝试从外部脚本执行代码,但是有这样的错误: Unchecked runtime.lastError while running tabs.executeScript: No source code or file specified at Object.callback
这是我的manifest.json:
{
"name": "Extension name",
"version": "1.2",
"description": "My chrome extension",
"browser_action": {
"default_popup": "popup.html",
},
"content_scripts": [{
"css": [
"style.css"
],
"js": [
"bower_components/jquery/dist/jquery.js",
"bower_components/bootstrap/dist/js/bootstrap.js",
"content.js"
],
"matches": ["*://*/*"]
}],
"web_accessible_resources": [
"frame.html",
"logo-48.png"
],
"icons": {
"16": "logo-16.png",
"48": "logo-48.png",
"128": "logo-128.png"
},
"permissions": [
"tabs",
"storage",
"http://*/",
"https://*/"
],
"manifest_version": 2
Run Code Online (Sandbox Code Playgroud)
}
这是popup.html
<!doctype html>
<html>
<head>
<title>Title</title>
<script src="popup.js"></script>
</head>
<body>
<ul>
<li>Some link</li>
</ul>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在popup.js中我执行这样的脚本:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.executeScript(tabs[0].id, {file: "http://127.0.0.1:8000/static/plugin/somesite.js"});
});
Run Code Online (Sandbox Code Playgroud)
我错了什么,我错过了什么吗?或者我应该使用另一种方法来解决问题?
谷歌浏览器禁止从您尝试的外部来源运行脚本,并且会阻止甚至不发布您的扩展程序.所有脚本都必须在扩展名中.但是有一个解决方案, 来自谷歌Chrome文档:
对通过HTTP加载的资源的限制仅适用于直接执行的那些资源.例如,您仍然可以自由地将XMLHTTPRequest连接到您喜欢的任何来源; 默认策略不以任何方式限制connect-src或任何其他CSP指令.
如果您需要一个非常外部的源,您可以执行XML HTTP请求并使用eval来处理内容.以下是google doc的一部分代码:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:8000/static/plugin/somesite.js", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// WARNING! Might be evaluating an evil script!
var resp = eval("(" + xhr.responseText + ")");
// Or this if it's work
chrome.tabs.executeScript(tabs[0].id, {code: xhr.responseText});
}
}
xhr.send();
Run Code Online (Sandbox Code Playgroud)
或者你可以使用一些库,带有jquery的$ .get()或带有angularjs的$ http.如果在代码中添加eval,则必须在manifest.json中添加:
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"`,
Run Code Online (Sandbox Code Playgroud)
按照这里的讨论:https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/LIH7LGXeQHo,
从外部源运行脚本可能会导致您的扩展程序未发布或被阻止.
只需提供另一种方法,您可以对内容脚本进行ajax调用,然后调用 chrome.tabs.executeScript
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
$.get("http://127.0.0.1:8000/static/plugin/somesite.js", function(result) {
chrome.tabs.executeScript(tabs[0].id, {code: result});
}, "text");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9700 次 |
| 最近记录: |