将 JQuery 加载到 Chrome 扩展程序中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4947510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:14:54  来源:igfitidea点击:

Load JQuery into a Chrome extension?

jquerygoogle-chrome-extension

提问by Skizit

I'm attempting to load JQuery into my Chrome extension and make it equal to an object but I'm wondering how would I go about this? basically I'd like something like...

我正在尝试将 JQuery 加载到我的 Chrome 扩展程序中并使其等于一个对象,但我想知道我将如何处理?基本上我想要像......

jQuery = loadLibraries("jquery-1.4.2.min.js");

How would I do this?

我该怎么做?

edit: I'm injecting into content script.

编辑:我正在注入内容脚本。

回答by serg

You can just put jquery.js into extension folder and include it in the manifest:

您可以将 jquery.js 放入扩展文件夹并将其包含在清单中:

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"]
    }
  ],
  ...
}

You don't need to worry about conflicts with jQuery on a parent page as content scripts are sandboxed.

您无需担心与父页面上的 jQuery 冲突,因为内容脚本是沙盒化的。

回答by jdc

You can do this from a script in your background_page HTML:

您可以从 background_page HTML 中的脚本执行此操作:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, { file: "jquery.min.js" }, function() {
    chrome.tabs.executeScript(null, { file: "content_script.js" });
  });
});

Then in content_script.js do whatever you like:

然后在 content_script.js 中做任何你喜欢的事情:

  $('#header').hide();

Note that even if the page you've injected into already has jQuery loaded, you're still hitting your own instance of the jQuery object, which is accessing the page via the DOM. (document).

请注意,即使您注入的页面已经加载了 jQuery,您仍然会访问您自己的 jQuery 对象实例,它通过 DOM 访问页面。(文档)。

回答by Ankush Ganatra

"content_scripts": [ {
    "matches": ["http://*/*"],
    "js": ["jquery.min.js"]
} ]

回答by Please treat your mods well.

Check the answer by jdchere in this same thread.

在同一线程中检查jdc答案

Edit: this answer was pretty old and did not reflect current practices anymore. Thank you for the heads up.

编辑:这个答案已经很旧了,不再反映当前的做法。谢谢你的提醒。