如何使用Manifest V3的Chrome扩展程序注入jQuery

5
我需要从内容脚本运行一些jQuery代码,但有些网站没有包含jQuery,有没有办法注入它? 我尝试了这个方法,但似乎根本不起作用。
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
1个回答

9

是的。

如果您想在body之前访问jquery,则在manifest.json文件中使用“document_start”而不是“document_end”。

答案1。

在manifest.json中将其包含在您的内容脚本之前。

  1. 下载您想要使用的jquery版本。
  2. 在manifest.json中指定它。

manifest.json

{
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<tab_url_pattern>"],
      "run_at": "document_end", 
      "js": ["jquery3.5.1.min.js", "contentScript.js"],
      "all_frames": false
    },
  ]
}

答案2.

使用 "Web_accessible_resource" 暴露 jQuery 文件,并使用 document.body.appendChild() 将其注入所需的选项卡中。

{
  "manifest_version":3,
  "permissions": ["tabs"],
  "content_scripts":[{
      "matches": ["<url_pattern_1>"],
      "run_at": "document_end",
      "js": ["contentScript.js"],
      "all_frames": false
    }],
    "web_accessible_resources": [
    {
      "resources": ["jquery-1.11.3.min.js", "otherJquery.js"],
      "matches": ["<url_pattern_1>"]
    }
  ]
}

在contentScript.js文件中

const contentScriptLinks = ['jquery-1.11.3.min.js', 'otherJquery.js'];

contentScriptLinks.forEach(src => {
  let el = document.createElement('script');
  el.src = chrome.runtime.getURL(src);
  document.body.appendChild(el);
});


同样的方法是否适用于从popup.html加载的popup.js中的弹出窗口?我收到了错误消息“拒绝执行内联事件处理程序,因为它违反以下内容安全策略指令:“script-src'self''wasm-unsafe-eval'”。需要使用“unsafe-inline”关键字、哈希('sha256-...')或nonce('nonce-...')来启用内联执行。 - Markus
1
是的,它应该可以工作。但是,如果我们在HTML文件中包含任何内联JavaScript,例如`onClick=doSomethingHandler()"或者在popup.html中包含任何其他内联JavaScript,它将会出现此错误。 - sadakchap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接