Using javascript to save an XHR file

I would like to save the JSON file that is requested on the page after login with a POST request. Since the API is not available, I would like to load the response of the called script when loading the page as a JSON file using Greasemonkey.

Page looks like domain.com/map, which causes domain.com/map/ script at boot time <script type="text/javascript" charset="utf-8"> function open() {$.ajax{{ url: "/script", type: "POST", dataType: "json",), [...] }); }; function functionname(value){ [...] }; open();. The domain.com/map/script answer is the actual JSON response I would like to save (locally or even better using FTP).

+4
source share
1 answer

full demo code below:

(function (fetch, console) {

    fetch('https://api.stackexchange.com/2.2/questions/36132760?site=stackoverflow')
        .then(res => res.json())
        .then(data => console.save(data));

    console.save = function (data, filename) {

            if (!data) {
                console.error('Console.save: No data')
                return;
            }

            if (!filename) filename = 'console.json'

            if (typeof data === "object") {
                data = JSON.stringify(data, undefined, 4);
            }

            var blob = new Blob([data], {type: 'text/json'}),
                e    = document.createEvent('MouseEvents'),
                a    = document.createElement('a');

            a.download = filename;
            a.href = window.URL.createObjectURL(blob);
            a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':');
            e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
    };

}).call(this, window.fetch, window.console || {});
Run codeHide result

checkout devtools-snippets # console-save

+3

All Articles