按照此处的文档:https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/downloads/download
var options = {
filename: 'dummyName.txt',
url: 'https://some.url',
conflictAction: 'uniquify',
saveAs: true
};
var downloading = browser.downloads.download(options, function() {
console.log('In callback');
});
console.log(downloading);
downloading.then(function() {
console.log('started');
}, function() {
console.log('failed');
});
在控制台中,我看到..
undefined
downloading is undefined
In callback
Unchecked lastError value: Error: Download canceled by the user
如果用户取消了对话框保存,如何阻止downloading.then
内的代码运行?
答案 0 :(得分:1)
实际上很简单。只需从下载功能中删除function()部分,如下所示:
var options = {
filename: 'dummyName.txt',
url: 'https://some.url',
conflictAction: 'uniquify',
saveAs: true
};
var downloading = browser.downloads.download(options);
console.log("downloading object is " + downloading);
downloading.then(function(id) {
console.log('started' + id);
}, function(error) {
if(error.message == "Download canceled by the user"){
// Do something
console.log("not going into the success callback..");
}else{
console.log('failed' + error);
}
});
您混合了回调语法(您在下载调用中包含的函数())和基于Promise的语法(然后是())。
如果您想要正确捕获错误,最好使用基于Promise的语法来开发Firefox插件。
请注意,您可以简化此
var downloading = browser.downloads.download(options);
downloading.then(onSuccess, onError);
到
browser.downloads.download(options).then(onSuccess, onError);
开发Firefox插件祝你好运!