javascriptgoogle-chrome-extensiondownloaddata-urifirefox-addon-webextensions

Save Data URI as file using downloads.download() API


Update

I have solved this problem (thanks to @DanielHerr) by using a Blob URL / Object-URL (URL.createObjectURL(blob)), however I am still curious to why this error exists when using data: URLs


I am creating a extension using the WebExtensions API, for both Chrome and Firefox.

The extension gathers data over time, and I would like to implement a feature to export it as a CSV file.

I tried using downloads.download() to download the file, however I get the error:

Error: Type error for parameter options (Error processing url: Error: Access denied for URL data:text/csv;charset=utf-8;base64,{data...}) for downloads.download.

I have tried adding "<all_urls>" to the permissions key in the manifest.json, however that makes no difference whatsoever.

This is the code I am using:

var csv = 'Hello, World!' // Real data goes here
var url = 'data:text/csv;charset=utf-8;base64,' +
           window.btoa(unescape(encodeURIComponent(csv)))

chrome.downloads.download({'url': url})

I cannot seem to work out how to resolve this issue, so I'll really appreciate the help! Thank you!


My manifest.json looks like this:

{
    "manifest_version": 2,
    "name": "Name",
    "version": "1.0.0",
    "description": "Description",
    "icons": {
        "16": "/icons/icon-16.png",
        "32": "/icons/icon-32.png",
        "48": "/icons/icon-48.png",
        "64": "/icons/icon-64.png",
        "96": "/icons/icon-96.png"
    },
    "applications": {
        "gecko": {
            "id": "@name",
            "strict_min_version": "48.0"
        }
    },
    "background": {
        "scripts": ["/scripts/a.js"]
    },
    "permissions": [
        "storage",
        "tabs",
        "activeTab",
        "downloads",
        "<all_urls>"
    ]
}

a.js contains the code to export as a CSV.

I stripped the rest of the code down so that only manifest.json, a.js and the icon files are left, but it still reported the same error.


Solution

  • I solved the problem by using a Blob URL / Object-URL instead of a Data URI:

    var csv = 'foo,bar,baz'
    var blob = new Blob([csv], {type: "text/csv;charset=utf-8"})
    
    chrome.downloads.download({
        'url': URL.createObjectURL(blob),
        'filename': 'file.csv',
    })