网页脚本 008:浏览器的当前HTML下载插件(支持单页应用)

// ==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 });
})(); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值