javascript – Chrome扩展程序:加载并执行外部脚本

前端之家收集整理的这篇文章主要介绍了javascript – Chrome扩展程序:加载并执行外部脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法在我的chrome扩展程序中加载和执行外部js-script.看起来和 this question一样,但我仍然无法弄清楚为什么它在我的情况下不起作用. @H_404_2@我的想法是,我希望在我的内容脚本中有一些默认函数,它应该解析网页内容.对于某些特定的网页,我想加载和使用特定的解析器,所以我尝试为wep页面加载正确的js-script,这个脚本应该扩展默认解析器的功能.

@H_404_2@到目前为止,我只尝试从外部脚本执行代码,但是有这样的错误:运行tabs.executeScript时未经检查的runtime.lastError:没有在Object.callback指定的源代码文件

@H_404_2@这是我的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
@H_404_2@}

@H_404_2@这是popup.html

<!doctype html>
 <html>
 <head>
  <title>Title</title>
  <script src="popup.js"></script>
 </head>
 <body>
  <ul>
    <li>Some link</li>
  </ul>
 </body>
</html>
@H_404_2@在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"});
});
@H_404_2@我错了什么,我错过了什么吗?或者我应该使用另一种方法解决问题?

解决方法

谷歌浏览器禁止像您尝试的外部来源运行脚本,并且会阻止甚至不发布您的扩展程序.所有脚本都必须在扩展名中.但有一个解决方案,
from google chrome doc
@H_404_2@The restriction against resources loaded over HTTP applies only to
those resources which are directly executed. You’re still free,for
example,to make XMLHTTPRequest connections to any origin you like;
the default policy doesn’t restrict connect-src or any of the other
CSP directives in any way.

@H_404_2@如果您需要一个非常外部的源,您可以执行XML HTTP请求并使用eval来处理内容.这是代码from 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();
@H_404_2@或者您可以使用某些库,$.get() with jquery$http with angularjs.
如果在代码添加eval,则必须在manifest.json中添加

"content_security_policy":  "script-src 'self' 'unsafe-eval'; object-src 'self'"`,

猜你在找的JavaScript相关文章