Skip to content

Instantly share code, notes, and snippets.

@jmg
Last active November 4, 2019 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmg/4c36e869039724585df1c98d7839343d to your computer and use it in GitHub Desktop.
Save jmg/4c36e869039724585df1c98d7839343d to your computer and use it in GitHub Desktop.
Envia un archivo a una nueva pestaña (child.html) mediante FileReader y postMessage
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<div>
<input onchange="readFileContent(this)" type="file" id="input-file">
</div>
<hr>
<div>
<button style="display: none"; onclick="sendFileToNewTab()" id="new-tab-button">Open new tab with file</button>
</div>
<script type="text/javascript">
//inicializo la variable donde se va a guardar el archivo en texto plano
var fileData = null;
function readFileContent(input) {
//FileReader es una clase que permite leer archivos directamente en el navegador sin tener que hacer un request a un servidor
//Mas information en https://developer.mozilla.org/en-US/docs/Web/API/FileReader
var reader = new FileReader()
reader.onload = function() {
//cuando el archivo es leido lo guardo en la variable fileData
fileData = reader.result;
//habilito el boton para enviarlo a la nueva pestaña
document.getElementById('new-tab-button').style = "display: block";
};
//metodo de FileReader que lee el archivo como texto plano
reader.readAsText(input.files[0]);
}
function sendFileToNewTab() {
if (!fileData) {
alert("file not loaded");
}
//abro una nueva pestaña en el navegador cargando el archivo "child.html"
childWindow = window.open("child.html", "_blank");
//esta funcion escucha eventos desde child.html
//esto es necesario para saber cuando child.html esta listo luego de abrirse
window.addEventListener('message', function(e) {
if (e.data == "ready") {
//cuando child.html envia el mensage "ready" entonces parent.html envia los datos del archivo en formato JSON
//Mas informacion en https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
childWindow.postMessage(JSON.stringify({"type": "file", "data": fileData}), '*');
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment