// ==UserScript== // @name Save Page Button // @namespace http://tampermonkey.net/ //…
- User
// ==UserScript== // @name Save Page Button // @namespace http://tampermonkey.net/ // @version 1.0 // @description Adds a button to save the current page. // @author Your Name // @match :///* // @grant GM_saveTab // @grant GM_getTab // ==/UserScript==
(function() { 'use strict';
code// 创建保存按钮 const saveButton = document.createElement('button'); saveButton.textContent = '保存当前页面'; // 设置按钮样式,使其位于右上角 saveButton.style.position = 'absolute'; saveButton.style.top = '20px'; saveButton.style.right = '10px'; saveButton.style.zIndex = '9999'; // 将按钮添加到页面上 document.body.appendChild(saveButton); // 为按钮添加点击事件处理函数 saveButton.addEventListener('click', saveCurrentPage); // 保存当前页面的函数 function saveCurrentPage() { console.log('保存按钮被点击'); const pageTitle = document.title; console.log('当前页面标题:', pageTitle); const fileName = pageTitle.replace(/[^\w\s]/gi, '') + '天翼云学堂.html'; console.log('生成的文件名:', fileName); const savePath = '/Users/weene/Downloads/' + fileName; console.log('保存路径:', savePath); GM_saveTab({ tabId: 'current', format: 'html', fileName: savePath }); }})(); 你是一个计算机软件专家,上面的代码试图在页面增加一个保存按钮并保存当前网页,但GM_saveTab并未被正确执行,请帮忙修改上面的代码
- Assistant
在Tampermonkey中,
GM_saveTab是一个不被直接支持的 API,因此不能用于保存网页。如果你想要保存网页的 HTML,可以通过其他方法实现,比如使用Blob和URL.createObjectURL来下载当前页面的内容。这里是修改后的代码,它会在点击按钮时生成网页的 HTML 文件并触发浏览器的下载功能:
javascript - User
console.log('保存按钮被点击'); const pageTitle = document.title; console.log('当前页面标题:', pageTitle); const fileName = pageTitle.replace(/[^\w\s]/gi, '') + '.html'; console.log('生成的文件名:', fileName); const blob = new Blob([document.documentElement.outerHTML], { type: 'text/html' }); const link = document.createElement('a'); 保存按钮被点击 当前页面标题: 天翼云学堂 生成的文件名: .html 生成的文件名不对
- Assistant
这个问题是由于生成的文件名字符串在通过
pageTitle.replace(/[^\w\s]/gi, '')处理后,掉出了所有的字符,导致fileName变成了一个空字符串。这样,最终生成的文件名变成了'.html',这是不被允许的。要解决这个问题,我们可以添加一些处理逻辑,以确保即使
pageTitle被替换后为空,也能赋予一个默认的文件名。以下是更新后的代码:javascript