gpt4 book ai didi

firefox-addon-webextensions - 如何以编程方式下载使用 Firefox WebExtension 创建的文件?

转载 作者:行者123 更新时间:2023-12-04 21:36:42 24 4
gpt4 key购买 nike

我正在尝试使用 Firefox 45.0.1 移植以编程方式创建文件并将文件下载到 Firefox WebExtension 的 Chrome 扩展程序。

这是Javascript代码:

  text = '{"greeting":"Hello, World!"}';
var a = document.createElement('a');
var file = new Blob([text], {type: 'text/json'});
a.href = URL.createObjectURL(file);
a.download = 'hello.world'; // Filename
a.click(); // Trigger download

所有行似乎都执行得很好,但没有下载文件(我在 console.log() 后面放了一个 a.click() )。

截至目前,Firefox WebExtensions 中没有 chrome.downloads API。

上面的代码中是否有与 Firefox 不兼容的地方?是否有其他替代方法可以使用 Firefox WebExtension 以编程方式下载文件?

最佳答案

一种方法是向 a 标记添加一个事件监听器。

text = '{"greeting":"Hello, World!"}';
var a = document.createElement('a');
var file = new Blob([text], {type: 'text/json'});
a.href = URL.createObjectURL(file);
a.download = 'hello.world'; // Filename
a.addEventListener('click', dlLinkClicked);


function dlLinkClicked(e){
var link = e.currentTarget.href;
var filename = e.currentTarget.download;

/*downloadVidWithChromeApi downloads using the chrome download API,
otherwise returns false and starts downloading the file
using the html5 download - you don't have to do anything else*/

if(downloadVidWithChromeApi(link, filename)){
e.preventDefault();
}
}

function downloadVidWithChromeApi(link, fileName){
if(chrome.downloads && chrome.downloads.download){
chrome.downloads.download({
url: link,
saveAs: false,
filename: fileName // Optional
});
return true;
}else{
return false;
}
}

请注意,我使用了 downloadVidWithChromeApi像这样的功能,检查是否支持 chrome.downloads。

因此,此代码可以按原样在 firefox、chrome 和 opera 网络扩展中运行。

关于firefox-addon-webextensions - 如何以编程方式下载使用 Firefox WebExtension 创建的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com