jsondownloadsapui5urlhelper

SAPUI5: Open JSON in new browser window fails


I would like to download JSON from my app to disk. For this purpose I am retrieving the JSON as encoded string from the backend and using this approach:

const uri = `data:text/json,${sJSONContent}`;
sap.m.URLHelper.redirect(uri, true);

This opens a new window but nothing is displayed and there is the error "Not allowed to navigate top frame to data URL" displayed in the new window's console.

What am I doing wrong?

Thanks


Solution

  • OK, I found it out myself. This is how to do it:

    // it is important to use the "data:" prefix and urlencode the data if necessary!
    const sData = `data:text/json;charset=utf-8,${sJSONContent}`;
    // create a HTML 'anchor' element
    const dummyAnchor = document.createElement('a');
    // add the data string as 'target' of that anchor
    dummyAnchor.setAttribute('href', sData);
    // set the 'download' attribute so that the browser treats the href as to be downloaded
    dummyAnchor.setAttribute('download', 'my.json');
    // add the dummyAnchor element to the document
    document.body.appendChild(dummyAnchor);
    // trigger clicking of that anchor element to start the download
    dummyAnchor.click();
    // remove the dummy again from the document to avoid side effects
    dummyAnchor.remove();
    

    I hope this will help someone else!