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

yiytaume  于 4个月前  发布在  Go
关注(0)|答案(1)|浏览(79)

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

{
  "manifest_version": 3,
  "name": "Chrome AI",
  "version": "0.0.1",
  "action": {
    "default_popup": "index.html",
    "default_icon": "chrome_ai.png"
  },
  "permissions": [
    "tabs",
    "activeTab",
    "scripting",
    "storage"
  ],
  "host_permissions": ["<all_urls>"]
}

字符串
index.html

<!doctype html>
<html lang="en">
<head>
    <title>Chrome AI</title>
    <script src="vendors/jquery-3.7.1.min.js"></script>
    <script defer src="index.js"></script>
</head>
<body>
<button id="gcal">Create Google Calendar Invite</button>
<code id="logs"></code>
</body>
</html>


index.js

$('#gcal').on('click', executeInTab(() => document.body.innerText).then(text => $('#logs').append(text)))

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

相关问题