fixed stuff included a fully working downloader for webpages which inlines the css / js. images do not work because they are hosted on the server
This commit is contained in:
@@ -1,18 +1,50 @@
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
// current page URL
|
||||
let url = window.location.href;
|
||||
const htmlDownload = document.getElementById("download-html");
|
||||
|
||||
// replace `/html/` with `/markdown/`
|
||||
url = url.replace("/html/", "/markdown/");
|
||||
htmlDownload.addEventListener("click", async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
// replace `.html` with `.md`
|
||||
url = url.replace(/\.html$/, ".md");
|
||||
const linkElements = document.querySelectorAll('link[rel="stylesheet"]');
|
||||
for (const link of linkElements) {
|
||||
const href = link.getAttribute("href");
|
||||
try {
|
||||
const res = await fetch(href);
|
||||
const cssText = await res.text();
|
||||
const styleEl = document.createElement("style");
|
||||
styleEl.textContent = cssText;
|
||||
document.head.appendChild(styleEl);
|
||||
link.remove(); // remove original link
|
||||
} catch (err) {
|
||||
console.error("Failed to inline CSS:", href, err);
|
||||
}
|
||||
}
|
||||
|
||||
// assign to <a>
|
||||
const a = document.getElementById("download-md");
|
||||
a.href = url;
|
||||
const scriptElements = document.querySelectorAll('script[src]');
|
||||
for (const script of scriptElements) {
|
||||
const src = script.getAttribute("src");
|
||||
try {
|
||||
const res = await fetch(src);
|
||||
const jsText = await res.text();
|
||||
const inlineScript = document.createElement("script");
|
||||
inlineScript.textContent = jsText;
|
||||
document.body.appendChild(inlineScript);
|
||||
script.remove(); // remove original script
|
||||
} catch (err) {
|
||||
console.error("Failed to inline JS:", src, err);
|
||||
}
|
||||
}
|
||||
|
||||
// suggest filename
|
||||
const filename = url.split("/").pop(); // e.g. markdowntest.md
|
||||
a.download = filename;
|
||||
const htmlContent = document.documentElement.outerHTML;
|
||||
|
||||
const blob = new Blob([htmlContent], { type: "text/html" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "index.html"; // or derive from URL
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user