Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

download html file client side with object with variables

Thanks to this post, I’ve been able to create an export button that download file on client side.
Now I’m trying to create an html page instead of a plain text file, and I encounter a lot of issues when I try to insert variables into it.
This is my code :

<a href="#" id="export-button" onclick="exports()">export</a>
<script src="example.js"></script>
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);
}

function exports() {
    let test_int = 10
    let test_str = 'hello world'
    let test_array = { "test": 10 }
    content = `<script>console.log(${test_array})</script>`
    download('export.html', content)
}

This is my error : Uncaught SyntaxError: Unexpected identifier 'Object' But I don’t have the error when I try to log some int
Anyway I hope my problem is understandable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you are using a Data URI, you also have to change the file’s type. If you just have a text file for your HTML, then you will just view the HTML as a text file. Also, if you want to print out an object then you have to stringify it to be readable.

function download(filename, text, file_type){
    file_type = file_type || 'TXT';
    var element = document.createElement('a');
    if(file_type == "HTML"){
        element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(text));
    }else{
        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);
}

function exports() {
    let test_int = 10
    let test_str = 'hello world'
    let test_array = { "test": 10 }
    content = `<script>console.log(${JSON.stringify(test_array)})</script>`
    download('export.html', content, 'HTML')
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading