【问题标题】:How to inject external script with chrome extention如何使用 chrome 扩展注入外部脚本
【发布时间】:2016-06-07 20:17:31
【问题描述】:

这是我第一次编写 Chrome 扩展程序。

我需要通过对当前页面使用 chrome 扩展来加载外部脚本。 现在我正在使用调试器模式(f12)加载脚本,在控制台选项卡中我正在运行 getScript("http://www.mypath.com/....") 我想通过单击 Chrome 扩展来传递所有这些.

到目前为止我所做的(通过阅读一些教程)是

manifest.json 文件

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "first extention",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery-1.12.4.min.js", "test.js"]
    }
  ],
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },

    "permissions": [ "tabs", "<all_urls>", "http://www.mypath.com*", "http://*/*", "https://*/*", "http://*.google.com/" ],
    "background": {
    "page": "background.html"
  },
     "content_security_policy": "script-src 'self' http://www.mypath.com; object-src 'self'"
}

popup.html 文件

 <html>
<head>
</head>
<body>
    <button id="btn" name="btn">click here</button>

    <script src="jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="test.js"></script>
</body>
</html>

test.js 文件

document.getElementById("btn").addEventListener("click", getUrl);
function getUrl() {  
jQuery.getScript("http://www.mypath.com/.....");
}

似乎它不起作用, 有人可以说明一下吗?

谢谢

【问题讨论】:

  • 由于 chrome 的安全问题,你会遇到各种问题。它可以使用正确的权限,但更好的方法是将脚本本地保存在扩展的目录中并从那里加载它。这可能吗?

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

试试这个:

test.js

 chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.executeScript(null,
                           {file:"http://www.mypath.com/....."});
    });

function getUrl() {  
chrome.tabs.executeScript(null,
                           {file:"http://www.mypath.com/....."});
}

manifest.json

"permissions": [
    "tabs", "http://www.mypath.com"
 ],

参考:https://developer.chrome.com/extensions/tabs#method-executeScript

【讨论】:

    猜你喜欢
    • 2011-10-03
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多