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
>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')
}