如何在清单v3扩展服务工作者中使用URL.CreateObjectUrl
我的扩展名创建了带有图像的拉链档案。然后我使用chrome.downloads.download下载我的存档到设备。
const url = URL.createObjectURL(archiveBlob);
chrome.downloads.download({
url,
filename: `${archiveData.fileName}.zip`,
saveAs: false
});
当我将ArrayBuffer转换为Image时,我的扩展程序中还需要URL.CreateObjectUrl
async bufferToImage(buffer: ArrayBuffer): Promise<InstanceType<typeof Image>> {
return new Promise((res, rej) => {
const blob = new Blob([buffer]);
const objectURL = URL.createObjectURL(blob);
const img = new Image();
img.src = objectURL;
img.onload = () => res(img);
});
}
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 blob 转换为 base64 。
如果要导出图像:
如果要导出zip:
You can convert Blob to base64.
If you want export image:
If you want export zip:
tl; dr:使用 data urls urls 。服务工作者没有
url.createobjectUrl
由于电位内存泄漏。什么是
url.createobjecturl
做什么?我们为什么使用它?这个小函数可以做一些我们可以将其与
chrome.download这样的功能以及函数以及函数一起使用的一些事情。
因为它需要一个斑点对象,所以我们已经提供了内容(参数1)和
类型
(参数2;选项)。url.createobjecturl
的返回值不仅是任何URL。此URL是您提供的内容的结果。尝试访问这些URL,这是您的内容托管。例如“ Hello world” =&gt;
url.createobjecturl
=&gt;blob:chrome-extension://.../&ult; uuid&gt;
=&gt; 现在, “ Hello World”,如我们的示例,当使用
chrome.downloads
时,将返回的URL值作为url
参数,文件类型和文件名是自动分配的,当您的内容被重新下载时。因此,如果您想复制此功能:
TL;DR: Use Data URLs. Service Workers do not have
URL.createObjectURL
due to potential memory leaks.What is
URL.createObjectURL
doing and why are we using it?This little function does a few things that we can take for granted when we use it along with functions like
chrome.download
.Because it requires a Blob object, we are already providing the content (argument 1) and the
type
(argument 2; options).The return value of
URL.createObjectURL
is not just any URL. This URL is the result of your provided content being stored. Try visiting these URLs, it is your content being hosted.e.g. "hello world" =>
URL.createObjectURL
=>blob:chrome-extension://.../<uuid>
=> "hello world"Now, as for our example when using
chrome.downloads
, by providing the returned URL value as theurl
parameter, the file type and file name are automatically assigned, when your content is being retried to download.Thus, if you want to replicate this functionality:
在Chrome扩展中不允许通过消息直接传递
BLOB
对象。您可以将
blob
对象转换为基本64编码的字符串。这是如何进行转换的示例:在
背景
脚本中,将blob
转换为base64String
:在
content脚本,接收
base64String
,然后转换回blob
:Passing
Blob
objects directly via Message is not allowed in Chrome extensions.You can convert a
Blob
object to a base64-encoded string. Here's an example of how to do the conversion:In the
background
script, convert theblob
to abase64String
:In the
content
script, receive thebase64String
and convert back to ablob
: