// ==UserScript==
// @name HTML下载器
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 添加按钮下载页面HTML代码
// @author Your name
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 创建下载按钮
function createDownloadButton() {
const button = document.createElement('button');
button.innerHTML = '下载HTML';
button.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
// 添加悬停效果
button.onmouseover = function() {
this.style.backgroundColor = '#45a049';
};
button.onmouseout = function() {
this.style.backgroundColor = '#4CAF50';
};
// 点击事件处理
button.onclick = function() {
downloadHTML();
};
document.body.appendChild(button);
}
// 下载HTML内容
function downloadHTML() {
// 获取完整的HTML内容
const htmlContent = document.documentElement.outerHTML;
// 创建Blob对象
const blob = new Blob([htmlContent], { type: 'text/html' });
// 创建下载链接
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
// 设置文件名(使用当前页面标题或域名)
const fileName = (document.title || window.location.hostname) + '.html';
a.href = url;
a.download = fileName;
// 触发下载
document.body.appendChild(a);
a.click();
// 清理
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
// 当页面加载完成时创建按钮
window.addEventListener('load', createDownloadButton);
// 监听页面变化(用于单页应用)
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
// 确保按钮只添加一次
const existingButton = document.querySelector('button');
if (!existingButton) {
createDownloadButton();
}
}
}).observe(document, { subtree: true, childList: true });
})();
网页脚本 008:浏览器的当前HTML下载插件(支持单页应用)
于 2024-12-14 19:00:00 首次发布