Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox WebExtension API "downloads" not working

I want to create my own extension, which automatically downloads files from certain websites and saves it in the default downloads folder. I started with the "your first extension" example that creates a red border around the page. This worked!

Then I tried to use this example, which explains the download function, to download an image from google server and it just won't work. I also added a permission for "downloads" API in the manifest.json, but it does not help. The code breaks and everything after browser.downloads.download is not executed.

I also tried console.log(browser); and console.log(browser.downloads);. The browser object is defined, but browser.downloads is undefined.

Here is the code:

manifest.json:

{

"manifest_version": 2,
"name": "Permission Test",
"version": "1.0",

"description": "Downloads an image",

"applications": {
    "gecko": {
        "id": "[email protected]"
    }
},

"icons": {
    "48": "icons/border-48.png"
},

"permissions": [
    "activeTab",
    "downloads"
],

"content_scripts": [
    {
    "matches": ["*://www.google.de/logos/doodles/2018/*"],
    "js": ["script.js"]
    }
]

}

script.js:

document.body.style.border = "10px solid red";
console.log('Extension started.');


function onStartedDownload(id) {
    console.log('Started downloading: ${id}');
}

function onFailed(error) {
    console.log('Download failed: ${error}');
}

var downloadUrl = "https://www.google.de/logos/doodles/2018/virginia-woolfs-136th-birthday-5857012284915712.6-l.png";

console.log(browser.downloads);

var downloading = browser.downloads.download({
    url: downloadUrl
    //filename: 'my-image-again.gif',
    conflictAction: 'uniquify'
});

downloading.then(onStartedDownload, onFailed);

console.log('Extension execution finished.');

I am using Firefox 58 and Windows 7.

like image 822
Chris Avatar asked Jan 02 '23 21:01

Chris


1 Answers

The downloads API is not available in content scripts, you probably want to move that code to a background page. I would start by reading this page to familiarize yourself with the overall structure of WebExtensions: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension

like image 70
Andrew Swan Avatar answered Jan 13 '23 14:01

Andrew Swan