Greasy Fork is available in English.

关闭时自动保存网页文本

历史记录增强版,关闭标签页时,自动保存历史网页的内容。按下alt+O键,下载保存的所有内容。仅保存纯文本和图片链接。相关:Wayback Machine archive.org Internet Archive singlefile。singlefile还会多保存一些html标签,占用大小会更大。

// ==UserScript==
// @name         关闭时自动保存网页文本
// @namespace    http://tampermonkey.net/
// @version      2024-05-30
// @description  历史记录增强版,关闭标签页时,自动保存历史网页的内容。按下alt+O键,下载保存的所有内容。仅保存纯文本和图片链接。相关:Wayback Machine archive.org Internet Archive singlefile。singlefile还会多保存一些html标签,占用大小会更大。
// @author       You
// @match        https://www.xiaohongshu.com/*
// @match        https://www.google.com/*
// @match        https://www.google.com.hk/*
// @match        https://www.bilibili.com/*
// @match        https://www.douyin.com/*
// @match        https://www.baidu.com/*
// @match        https://*.zhihu.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=xiaohongshu.com
// @grant    GM_setValue
// @grant    GM_listValues
// @grant    GM_getValue
// @grant    GM_deleteValue
// @grant    GM_notification
// @require https://update.greasyfork.org/scripts/496125/1383400/util%E5%BA%93.js
// @license MIT
// ==/UserScript==


function getImgSrc() {
	// 获取当前页面中所有拥有background-image属性的元素
	const elementsWithBackgroundImage = document.querySelectorAll('[style*="background-image"]');
	let backgroundImageValue = "";
	// 遍历这些元素,获取并输出backgroundImage属性的值
	elementsWithBackgroundImage.forEach(function (element) {
		// 注意:backgroundImage可能是一个CSS样式规则,而不是element.style属性
		// 因此,我们需要使用getComputedStyle来获取实际的样式值
		const computedStyle = window.getComputedStyle(element);
		backgroundImageValue += "\n" + computedStyle.getPropertyValue('background-image');

	});
	console.log(backgroundImageValue);


	// 获取当前页面中所有<img>元素的src属性
	const imgElements = document.querySelectorAll('img');

	// 初始化一个空字符串来存储src值
	let srcString = '';

	// 遍历所有<img>元素
	imgElements.forEach(function (imgElement) {
		// 获取每个<img>元素的src属性
		const srcValue = imgElement.src;

		// 将src值添加到字符串中,并以换行符\n分隔
		srcString += srcValue + '\n';
	});

	// 输出拼接后的src字符串
	// console.log(srcString);

	return backgroundImageValue + "\n" + srcString;

}

function savePageDataBeforeUnload() {
	// 获取当前页面的URL
	const currentUrl = window.location.href;

	// 获取当前页面的标题
	const pageTitle = document.title;

	// 获取当前页面的内容
	const pageContent = document.body.innerText;

	// 输出当前网页的URL、标题和内容
	console.log('Current URL:', currentUrl);
	console.log('Page Title:', pageTitle);
	console.log('Page Content:', pageContent);

	let totalImgSrc = getImgSrc()

	GM_setValue(currentUrl, pageTitle + "\n" + pageContent + "\n" + totalImgSrc);
}

// 绑定beforeunload事件到savePageDataBeforeUnload函数
window.addEventListener('beforeunload', savePageDataBeforeUnload);

document.addEventListener('keydown', (e) => {
	if (e.altKey && e.keyCode === 79) { // alt和O 77M 78N 79O
		// 下载为json文件
		savedJson('savedInnerText_')
	}
})