在Chrome扩展中使用CDN JavaScript库(manifest v3)

yiytaume  于 2024-01-04  发布在  Go
关注(0)|答案(1)|浏览(358)

我有一个简单的Chrome扩展程序,它使用ChatGPT分析页面并创建Google日历邀请。完整的源代码是here,但这里是代码的核心,当点击时读取当前页面的文本:
manifest.json

  1. {
  2. "manifest_version": 3,
  3. "name": "Chrome AI",
  4. "version": "0.0.1",
  5. "action": {
  6. "default_popup": "index.html",
  7. "default_icon": "chrome_ai.png"
  8. },
  9. "permissions": [
  10. "tabs",
  11. "activeTab",
  12. "scripting",
  13. "storage"
  14. ],
  15. "host_permissions": ["<all_urls>"]
  16. }

字符串
index.html

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <title>Chrome AI</title>
  5. <script src="vendors/jquery-3.7.1.min.js"></script>
  6. <script defer src="index.js"></script>
  7. </head>
  8. <body>
  9. <button id="gcal">Create Google Calendar Invite</button>
  10. <code id="logs"></code>
  11. </body>
  12. </html>


index.js

  1. $('#gcal').on('click', executeInTab(() => document.body.innerText).then(text => $('#logs').append(text)))
  2. executeInTab = (f) => chrome.tabs.query({active: true, lastFocusedWindow: true})
  3. .then(([tab]) => chrome.scripting.executeScript({target: {tabId: tab.id}, function: f}))
  4. .then(([{ result }]) => result)


但是,正如你所看到的,这需要我在vendors/jquery-3.7.1.min.js下下载并签入jquery。由于it is a bad practice to check in library dependencies到你的仓库(同样的原因,你不签入你的node_modules),我更喜欢简单地使用像jsdelivr这样的CDN来托管我的库。但是,当我尝试添加<script src="https://cdn.jsdelivr.net/npm/ [[email protected]](https://stackoverflow.com/cdn-cgi/l/email-protection) /dist/jquery.min.js"></script>时,我得到以下错误:

在有人把这个问题作为重复问题关闭之前,下面是为什么其他答案不起作用:

1.在this中,接受的答案是针对manifest v2的,而我在manifest v3上。那里发布的v3答案根本不起作用(我在这里发布的代码做了那里的建议)。

  1. This询问如何将jquery加载到活动选项卡窗口中,而不是真正作为扩展本身的依赖项
  2. Thisthisthisthis询问如何将库加载到内容和后台工作程序中,而不是加载到弹出窗口本身。FWIW,这些都是彼此的重复,而不是这个问题的重复!
  3. This one的措辞很差,没有答案,使用了manifest v2
esyap4oy

esyap4oy1#

为了提高安全性,Chrome已经在Manifest V3的扩展中删除了对CDN的支持,或者任何其他使用远程托管JavaScript的方式。
他们有一些他们推荐的解决方案:

  • 您还可以在运行时加载外部库,方法是在调用scripting.executeScript()时将它们添加到文件数组中。您仍然可以在运行时远程加载数据:
  1. chrome.scripting.executeScript({
  2. target: {tabId: tab.id},
  3. files: ['jquery.min.js']
  4. });
  • 只要将文件作为扩展的一部分捆绑即可。我知道根据你找到的文章,这被视为不好的做法,但它对用户的影响很小,而且Chrome文档似乎没有问题。
  1. <script src="./jquery.min.js"></script>

相关问题