0
votes

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?

1

1 Answers

0
votes

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.