📅  最后修改于: 2023-12-03 15:06:41.239000             🧑  作者: Mango
本文将介绍如何创建一个 Chrome Extension,以递归方式将所有 html 页面下载为单个文件。该扩展可以在 Chrome 浏览器中运行,并支持多个页面下载。
要实现本文所述的扩展,需要实现以下功能:
要创建 Chrome Extension,需要先创建一个目录,该目录将包含扩展所需的所有文件。
{
"name": "HTML Downloader",
"version": "1.0",
"manifest_version": 2,
"description": "Download all HTML pages as a single file.",
"icons": {
"16": "icon-16.png",
"32": "icon-32.png",
"48": "icon-48.png",
"128": "icon-128.png"
},
"browser_action": {
"default_icon": {
"16": "icon-16.png",
"32": "icon-32.png",
"48": "icon-48.png",
"128": "icon-128.png"
},
"default_title": "HTML Downloader"
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML Downloader</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 14px;
}
#status {
display: none;
}
#result {
display: none;
width: 100%;
height: 200px;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="status">Loading...</div>
<form id="form">
<label for="url">URL:</label>
<input type="text" id="url" name="url">
<button type="submit">Download</button>
</form>
<textarea id="result" readonly></textarea>
<script src="popup.js"></script>
</body>
</html>
function download(content, fileName, contentType) {
const a = document.createElement("a");
const file = new Blob([content], { type: contentType });
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
function downloadHtml(url) {
return fetch(url)
.then(res => res.text());
}
function downloadAllHtml(url) {
return downloadHtml(url)
.then(html => {
const linkMatches = html.match(/href="(.*?)"/g) || [];
const links = linkMatches.map(match => match.substring(6, match.length - 1))
.filter(link => !link.includes("javascript"));
const htmlPromises = links.map(link =>
downloadAllHtml(new URL(link, url).href)
);
return Promise.all(htmlPromises)
.then(htmls => [html, ...htmls]);
});
}
window.onload = () => {
const form = document.forms["form"];
form.onsubmit = event => {
event.preventDefault();
const url = form.elements["url"].value;
const status = document.getElementById("status");
const result = document.getElementById("result");
status.style.display = "block";
result.style.display = "none";
downloadAllHtml(url)
.then(htmls => {
const content = htmls.join("\n");
download(content, "index.html", "text/html");
status.style.display = "none";
result.style.display = "block";
result.value = content;
});
};
};
这些代码包括以下功能:
现在你可以在 Chrome 浏览器中浏览该扩展程序。从 Chrome 扩展商店中获取该扩展程序,并将其添加到 Chrome 浏览器中即可。
使用该扩展程序,你需要:
本文介绍了如何创建一个 Chrome Extension,以递归方式将所有 HTML 页面下载为单个文件。这个扩展可以帮助你轻松地下载一个网站的全部 HTML 页面并保存为一个单一的文件。希望这篇文章对您有所帮助。