从页面标题中删除指定的字符,脚本菜单里输入需要删除的字符
当前为
// ==UserScript==
// @name 清理网页标题字符
// @version 1.0
// @author ChatGPT
// @description 从页面标题中删除指定的字符,脚本菜单里输入需要删除的字符
// @match *://*/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_registerMenuCommand
// @namespace https://greasyfork.org/users/452911
// ==/UserScript==
(function() {
'use strict';
const DEFAULT_FILTERS = '';
// 过滤函数:接收网页标题和需要清除的字符过滤器数组作为参数,并返回一个已经过滤掉所有指定字符的标题。
function cleanTitle(title, filters) {
let cleanedTitle = title;
for (let i = 0; i < filters.length; i++) {
cleanedTitle = cleanedTitle.replaceAll(filters[i], '');
}
return cleanedTitle;
}
// 获取用户设置的字符过滤器。如果没有设置过,则使用默认的字符过滤器(在本例中是 & 和 -)。
function getConfiguredFilters() {
let filters = GM_getValue('filters');
if (!filters) {
filters = DEFAULT_FILTERS;
GM_setValue('filters', filters);
}
return filters.split('&');
}
// 将“清除字符”选项添加到油猴脚本菜单中
function setConfiguredFilters() {
const currentFilters = getConfiguredFilters(); // 获取当前字符过滤器
let newFilters = prompt('输入需要删除的字符(用 & 分隔)或留空使用默认值:', currentFilters.join('&')); // 将当前字符过滤器传递给 prompt 方法
if (newFilters === null) {
return;
}
if (newFilters === '') {
newFilters = DEFAULT_FILTERS;
}
GM_setValue('filters', newFilters);
window.location.reload(); // 保存设置并重新加载页面,以便应用新的过滤器设置。
}
// 注册“清除字符”选项
GM_registerMenuCommand('清理网页标题字符 - 编辑过滤器', setConfiguredFilters);
const filters = getConfiguredFilters();
// 在页面加载时使用过滤函数清理页面标题
document.title = cleanTitle(document.title, filters);
})();