Website from zip file renderer – problems with nested dependencies from blob

I have been working on a solution to render a webpage (with dependencies etc) from a zip file.

I have gotten sofar that it renders most things relatively well,

But inline scripts that fetch yet other content (f.e. jquery document load html, which loads yet another local file) still throw ERR_FILE_NOT Found.

Sofar this is my effort:
https://codepen.io/ryedai1/pen/jOjNjVR

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!DOCTYPE html>
<html>
<head>
<title>JSZip Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
<script>
if (typeof JSZip === 'undefined') {
document.write('<script src="jszip.min.js"></script>');
}
document.addEventListener("DOMContentLoaded", async function () {
const url = "https://alcea-wisteria.de/z_files/alceawis.de.zip";
const fileListElement = document.getElementById("file-list");
function sanitizeFileName(fileName) {
return fileName.replace(/[^a-zA-Z0-9.-]/g, '_');
}
async function getFileType(fileName) {
const extension = fileName.split('.').pop().toLowerCase();
switch (extension) {
case 'html':
case 'htm':
return 'text/html';
case 'css':
return 'text/css';
case 'js':
return 'application/javascript';
case 'json':
return 'application/json';
case 'png':
return 'image/png';
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'gif':
return 'image/gif';
case 'svg':
return 'image/svg+xml';
default:
return 'application/octet-stream';
}
}
async function processScriptContent(content, fileMap) {
fileMap.forEach(({ relativePath, absolutePath }) => {
const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'g');
content = content.replace(regex, absolutePath);
});
content = content.replace(/fetch(['"]([^'"]+)['"])/g, (match, p1) => {
const file = fileMap.find(entry => entry.relativePath === p1);
if (file) {
return `fetch('${file.absolutePath}')`;
} else {
return match;
}
});
content = content.replace(/['"]([^'"]+.(json|xml|csv|txt|png|jpg|jpeg|gif|svg))['"]/g, (match, p1) => {
const file = fileMap.find(entry => entry.relativePath === p1);
if (file) {
return `'${file.absolutePath}'`;
} else {
return match;
}
});
return content;
}
async function loadHtmlContent(content, fileMap) {
let modifiedContent = content;
fileMap.forEach(({ relativePath, absolutePath }) => {
const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'g');
modifiedContent = modifiedContent.replace(regex, absolutePath);
});
const tempElement = document.createElement('div');
tempElement.innerHTML = modifiedContent;
tempElement.querySelectorAll('iframe').forEach(iframe => {
const src = iframe.getAttribute('src');
const file = fileMap.find(entry => entry.relativePath === src);
if (file) {
iframe.setAttribute('src', file.absolutePath);
}
});
tempElement.querySelectorAll('a').forEach(anchor => {
const href = anchor.getAttribute('href');
if (href && !href.startsWith('http')) {
const file = fileMap.find(entry => entry.relativePath === href);
if (file) {
anchor.setAttribute('href', file.absolutePath);
anchor.setAttribute('target', '_self');
}
}
});
const scriptPromises = [];
tempElement.querySelectorAll('script').forEach(script => {
const src = script.getAttribute('src');
if (src) {
const file = fileMap.find(entry => entry.relativePath === src);
if (file) {
const newScript = document.createElement('script');
newScript.src = file.absolutePath;
newScript.type = 'application/javascript';
script.replaceWith(newScript);
}
} else {
scriptPromises.push(new Promise(async (resolve) => {
const scriptContent = await processScriptContent(script.textContent, fileMap);
const newScript = document.createElement('script');
newScript.textContent = scriptContent;
script.replaceWith(newScript);
resolve();
}));
}
});
await Promise.all(scriptPromises);
document.open();
document.write(tempElement.innerHTML);
document.close();
}
try {
const response = await fetch(url);
if (!response.ok) throw new Error("Failed to fetch the zip file.");
const blob = await response.blob();
const zip = await JSZip.loadAsync(blob);
const fileMap = [];
for (const [relativePath, file] of Object.entries(zip.files)) {
if (!file.dir) {
const fileContent = await file.async("blob");
const fileType = await getFileType(relativePath);
const objectUrl = URL.createObjectURL(new Blob([fileContent], { type: fileType }));
fileMap.push({ relativePath, absolutePath: objectUrl });
}
}
fileListElement.textContent = fileMap.map(entry => entry.relativePath).join("n");
const indexPath = "index.html";
const indexFile = fileMap.find(entry => entry.relativePath === indexPath);
if (indexFile) {
try {
const response = await fetch(indexFile.absolutePath);
const indexContent = await response.text();
await loadHtmlContent(indexContent, fileMap);
} catch (error) {
console.error(`Error loading ${indexPath} from object URL. Trying to load from zip blob.`);
console.error(error);
console.log(`Refetching ${indexFile.relativePath} from zip blob.`);
const indexContent = await indexFile.blob();
const textContent = await new Response(indexContent).text();
await loadHtmlContent(textContent, fileMap);
}
} else {
throw new Error(`${indexPath} not found in the zip file.`);
}
} catch (error) {
fileListElement.textContent = "Error: " + error.message;
}
});
</script>
</head>
<body>
<h1>JSZip Example</h1>
<pre id="file-list"></pre>
</body>
</html>
</code>
<code><!DOCTYPE html> <html> <head> <title>JSZip Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script> <script> if (typeof JSZip === 'undefined') { document.write('<script src="jszip.min.js"></script>'); } document.addEventListener("DOMContentLoaded", async function () { const url = "https://alcea-wisteria.de/z_files/alceawis.de.zip"; const fileListElement = document.getElementById("file-list"); function sanitizeFileName(fileName) { return fileName.replace(/[^a-zA-Z0-9.-]/g, '_'); } async function getFileType(fileName) { const extension = fileName.split('.').pop().toLowerCase(); switch (extension) { case 'html': case 'htm': return 'text/html'; case 'css': return 'text/css'; case 'js': return 'application/javascript'; case 'json': return 'application/json'; case 'png': return 'image/png'; case 'jpg': case 'jpeg': return 'image/jpeg'; case 'gif': return 'image/gif'; case 'svg': return 'image/svg+xml'; default: return 'application/octet-stream'; } } async function processScriptContent(content, fileMap) { fileMap.forEach(({ relativePath, absolutePath }) => { const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'g'); content = content.replace(regex, absolutePath); }); content = content.replace(/fetch(['"]([^'"]+)['"])/g, (match, p1) => { const file = fileMap.find(entry => entry.relativePath === p1); if (file) { return `fetch('${file.absolutePath}')`; } else { return match; } }); content = content.replace(/['"]([^'"]+.(json|xml|csv|txt|png|jpg|jpeg|gif|svg))['"]/g, (match, p1) => { const file = fileMap.find(entry => entry.relativePath === p1); if (file) { return `'${file.absolutePath}'`; } else { return match; } }); return content; } async function loadHtmlContent(content, fileMap) { let modifiedContent = content; fileMap.forEach(({ relativePath, absolutePath }) => { const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'g'); modifiedContent = modifiedContent.replace(regex, absolutePath); }); const tempElement = document.createElement('div'); tempElement.innerHTML = modifiedContent; tempElement.querySelectorAll('iframe').forEach(iframe => { const src = iframe.getAttribute('src'); const file = fileMap.find(entry => entry.relativePath === src); if (file) { iframe.setAttribute('src', file.absolutePath); } }); tempElement.querySelectorAll('a').forEach(anchor => { const href = anchor.getAttribute('href'); if (href && !href.startsWith('http')) { const file = fileMap.find(entry => entry.relativePath === href); if (file) { anchor.setAttribute('href', file.absolutePath); anchor.setAttribute('target', '_self'); } } }); const scriptPromises = []; tempElement.querySelectorAll('script').forEach(script => { const src = script.getAttribute('src'); if (src) { const file = fileMap.find(entry => entry.relativePath === src); if (file) { const newScript = document.createElement('script'); newScript.src = file.absolutePath; newScript.type = 'application/javascript'; script.replaceWith(newScript); } } else { scriptPromises.push(new Promise(async (resolve) => { const scriptContent = await processScriptContent(script.textContent, fileMap); const newScript = document.createElement('script'); newScript.textContent = scriptContent; script.replaceWith(newScript); resolve(); })); } }); await Promise.all(scriptPromises); document.open(); document.write(tempElement.innerHTML); document.close(); } try { const response = await fetch(url); if (!response.ok) throw new Error("Failed to fetch the zip file."); const blob = await response.blob(); const zip = await JSZip.loadAsync(blob); const fileMap = []; for (const [relativePath, file] of Object.entries(zip.files)) { if (!file.dir) { const fileContent = await file.async("blob"); const fileType = await getFileType(relativePath); const objectUrl = URL.createObjectURL(new Blob([fileContent], { type: fileType })); fileMap.push({ relativePath, absolutePath: objectUrl }); } } fileListElement.textContent = fileMap.map(entry => entry.relativePath).join("n"); const indexPath = "index.html"; const indexFile = fileMap.find(entry => entry.relativePath === indexPath); if (indexFile) { try { const response = await fetch(indexFile.absolutePath); const indexContent = await response.text(); await loadHtmlContent(indexContent, fileMap); } catch (error) { console.error(`Error loading ${indexPath} from object URL. Trying to load from zip blob.`); console.error(error); console.log(`Refetching ${indexFile.relativePath} from zip blob.`); const indexContent = await indexFile.blob(); const textContent = await new Response(indexContent).text(); await loadHtmlContent(textContent, fileMap); } } else { throw new Error(`${indexPath} not found in the zip file.`); } } catch (error) { fileListElement.textContent = "Error: " + error.message; } }); </script> </head> <body> <h1>JSZip Example</h1> <pre id="file-list"></pre> </body> </html> </code>
<!DOCTYPE html>
<html>
<head>
  <title>JSZip Example</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
  <script>
    if (typeof JSZip === 'undefined') {
      document.write('<script src="jszip.min.js"></script>');
    }
    
    document.addEventListener("DOMContentLoaded", async function () {
      const url = "https://alcea-wisteria.de/z_files/alceawis.de.zip";
      const fileListElement = document.getElementById("file-list");

      function sanitizeFileName(fileName) {
        return fileName.replace(/[^a-zA-Z0-9.-]/g, '_');
      }

      async function getFileType(fileName) {
        const extension = fileName.split('.').pop().toLowerCase();
        switch (extension) {
          case 'html':
          case 'htm':
            return 'text/html';
          case 'css':
            return 'text/css';
          case 'js':
            return 'application/javascript';
          case 'json':
            return 'application/json';
          case 'png':
            return 'image/png';
          case 'jpg':
          case 'jpeg':
            return 'image/jpeg';
          case 'gif':
            return 'image/gif';
          case 'svg':
            return 'image/svg+xml';
          default:
            return 'application/octet-stream';
        }
      }

      async function processScriptContent(content, fileMap) {
        fileMap.forEach(({ relativePath, absolutePath }) => {
          const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'g');
          content = content.replace(regex, absolutePath);
        });

        content = content.replace(/fetch(['"]([^'"]+)['"])/g, (match, p1) => {
          const file = fileMap.find(entry => entry.relativePath === p1);
          if (file) {
            return `fetch('${file.absolutePath}')`;
          } else {
            return match;
          }
        });

        content = content.replace(/['"]([^'"]+.(json|xml|csv|txt|png|jpg|jpeg|gif|svg))['"]/g, (match, p1) => {
          const file = fileMap.find(entry => entry.relativePath === p1);
          if (file) {
            return `'${file.absolutePath}'`;
          } else {
            return match;
          }
        });

        return content;
      }

      async function loadHtmlContent(content, fileMap) {
        let modifiedContent = content;
        fileMap.forEach(({ relativePath, absolutePath }) => {
          const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[]\]/g, '\$&'), 'g');
          modifiedContent = modifiedContent.replace(regex, absolutePath);
        });

        const tempElement = document.createElement('div');
        tempElement.innerHTML = modifiedContent;

        tempElement.querySelectorAll('iframe').forEach(iframe => {
          const src = iframe.getAttribute('src');
          const file = fileMap.find(entry => entry.relativePath === src);
          if (file) {
            iframe.setAttribute('src', file.absolutePath);
          }
        });

        tempElement.querySelectorAll('a').forEach(anchor => {
          const href = anchor.getAttribute('href');
          if (href && !href.startsWith('http')) {
            const file = fileMap.find(entry => entry.relativePath === href);
            if (file) {
              anchor.setAttribute('href', file.absolutePath);
              anchor.setAttribute('target', '_self');
            }
          }
        });

        const scriptPromises = [];
        tempElement.querySelectorAll('script').forEach(script => {
          const src = script.getAttribute('src');
          if (src) {
            const file = fileMap.find(entry => entry.relativePath === src);
            if (file) {
              const newScript = document.createElement('script');
              newScript.src = file.absolutePath;
              newScript.type = 'application/javascript';
              script.replaceWith(newScript);
            }
          } else {
            scriptPromises.push(new Promise(async (resolve) => {
              const scriptContent = await processScriptContent(script.textContent, fileMap);
              const newScript = document.createElement('script');
              newScript.textContent = scriptContent;
              script.replaceWith(newScript);
              resolve();
            }));
          }
        });

        await Promise.all(scriptPromises);

        document.open();
        document.write(tempElement.innerHTML);
        document.close();
      }

      try {
        const response = await fetch(url);
        if (!response.ok) throw new Error("Failed to fetch the zip file.");

        const blob = await response.blob();
        const zip = await JSZip.loadAsync(blob);

        const fileMap = [];
        for (const [relativePath, file] of Object.entries(zip.files)) {
          if (!file.dir) {
            const fileContent = await file.async("blob");
            const fileType = await getFileType(relativePath);
            const objectUrl = URL.createObjectURL(new Blob([fileContent], { type: fileType }));
            fileMap.push({ relativePath, absolutePath: objectUrl });
          }
        }

        fileListElement.textContent = fileMap.map(entry => entry.relativePath).join("n");

        const indexPath = "index.html";
        const indexFile = fileMap.find(entry => entry.relativePath === indexPath);
        if (indexFile) {
          try {
            const response = await fetch(indexFile.absolutePath);
            const indexContent = await response.text();
            await loadHtmlContent(indexContent, fileMap);
          } catch (error) {
            console.error(`Error loading ${indexPath} from object URL. Trying to load from zip blob.`);
            console.error(error);
            console.log(`Refetching ${indexFile.relativePath} from zip blob.`);
            const indexContent = await indexFile.blob();
            const textContent = await new Response(indexContent).text();
            await loadHtmlContent(textContent, fileMap);
          }
        } else {
          throw new Error(`${indexPath} not found in the zip file.`);
        }

      } catch (error) {
        fileListElement.textContent = "Error: " + error.message;
      }
    });
  </script>
</head>
<body>
  <h1>JSZip Example</h1>
  <pre id="file-list"></pre>
</body>
</html>

Any help is appreciated

PS:

In the link ther is a”take1″.

I used a different approach before, which handles dpendencies far better, but it kind of weird to apply to the current approach.

I also considered using service-worker(s), but lack the experience with them.

I tried to implement a fallback mechanism to redirect ERR_FILE_NOT_FOUND to the zip blob.
Sadly to no avail

New contributor

calipea is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật