Here is how I solved it for my application:
HTML: <a id="downloadAnchorElem" style="display:none"></a>
JS (pure JS, not jQuery here):
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj)); var dlAnchorElem = document.getElementById('downloadAnchorElem'); dlAnchorElem.setAttribute("href", dataStr ); dlAnchorElem.setAttribute("download", "scene.json"); dlAnchorElem.click();
In this case, storageObj is the js object you want to save, and "scene.json" is just an example of a name for the resulting file.
This approach has the following advantages over others offered:
- No HTML element need to click
- The result will be named the way you want.
- JQuery is not required
I needed this behavior without explicit clicking, since I want to automatically start the download at some point from js.
JS solution (HTML not required):
function downloadObjectAsJson(exportObj, exportName){ var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj)); var downloadAnchorNode = document.createElement('a'); downloadAnchorNode.setAttribute("href", dataStr); downloadAnchorNode.setAttribute("download", exportName + ".json"); document.body.appendChild(downloadAnchorNode);
volzotan Jun 12 '15 at 10:23 2015-06-12 10:23
source share