Skip to content

Instantly share code, notes, and snippets.

@CavaleriDK
Last active April 3, 2024 17:01
Show Gist options
  • Save CavaleriDK/ae0288754eb678c86896b1fa8e9a8fee to your computer and use it in GitHub Desktop.
Save CavaleriDK/ae0288754eb678c86896b1fa8e9a8fee to your computer and use it in GitHub Desktop.
function onInitialLoad(sourceFile) {
const parser = new DOMParser();
const initHTML = '<div id="your-files" style="background-color:#ff0000;width:500px;height:500px;"></div>';
const newDoc = parser.parseFromString(initHTML, "text/html");
document.replaceChild(newDoc.documentElement, document.documentElement);
const target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
event.preventDefault();
}, false);
target.addEventListener("drop", function(event) {
event.preventDefault();
let i = 0, files = event.dataTransfer.files, len = files.length;
for (; i < len; i++) {
loadFile(files[i]);
}
}, false);
};
onInitialLoad();
function loadFile(readThis) {
const reader = new FileReader();
const parser = new DOMParser();
reader.onload = function(event) {
let contents = event.target.result;
const newDoc = parser.parseFromString(contents, "text/html");
document.replaceChild(newDoc.documentElement, document.documentElement);
enableScripts();
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(readThis);
};
function enableScripts() {
const tmpScripts = document.getElementsByTagName('script');
if (tmpScripts.length > 0) {
// push all of the document's script tags into an array
// (to prevent dom manipulation while iterating over dom nodes)
const scripts = [];
for (let i = 0; i < tmpScripts.length; i++) {
scripts.push(tmpScripts[i]);
}
// iterate over all script tags and create a duplicate tags for each
for (let i = 0; i < scripts.length; i++) {
const s = document.createElement('script');
s.innerHTML = scripts[i].innerHTML;
// add the new node to the page
scripts[i].parentNode.appendChild(s);
// remove the original (non-executing) node from the page
scripts[i].parentNode.removeChild(scripts[i]);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment