0

I encountered an issue with my code under Mi browser. I cannot find a vanilla javascript solution to download a part of my page as html. The code that is functional on Chrome or Firefox doesn't work in Mi. Part of my code:

var elHtml = ""+document.getElementById("hlavicka").innerHTML +""+ document.getElementById("stranka").innerHTML + "";
        
    if (navigator.msSaveBlob) { // IE 10+ 
        navigator.msSaveBlob(new Blob([elHtml], { type: mimeType + ';charset=utf-8;' }), filename);
    } else {
        var link = document.createElement('a');
      document.body.appendChild(link); 
        mimeType = mimeType || 'text/plain';

        link.setAttribute('download', filename);
        link.setAttribute('href', 'data:' + mimeType  +  ';charset=utf-8,' + encodeURIComponent(elHtml));
        link.click(); 
    }

Could you please give me a hint?

2 Answers2

0

Well, with pure JavaScript, you could do:

var yourElement = document.getElementById("yourElement");

download("example.html", yourElement.outerHTML);

function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}

Simply change the yourElement variable to the element you want to download. The download() function will automatically download a file with the HTML (within that element), as a html file. You can use a different file format, by changing the filename parameter in the function.

Nanoo
  • 836
  • 8
  • 16
  • Thank you but still mobile browser Mi which is default in Xiaomi says that download failed. Invalid URL. Other browsers like Firefox or Chrome work well with my code or the code you provided. It seems the browser behaves differently to others but I cannot se how. – PiKoZell Jun 30 '20 at 05:31
  • Oh right, I will look into a solution for Mi in that case. – Nanoo Jun 30 '20 at 07:30
0

I have the same issue and I have found solution: Mi browser doesn't support downloading file as data URI, so you have to upload the file to your server (I use AJAX and php) and then set the href attribute to the file location on your server: element.setAttribute('href', '/mifiles/'+filename);

After user download it, don't forget to remove the file from server.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 22 '21 at 09:37