洛谷私信自动选中对话框
代码// ==UserScript==
// @name Luogu Chat Better!
// @namespace http://tampermonkey.net/
// @version 2.1
// @author Forever_Rain
// @description 洛谷私信优化
// @icon https://cdn.luogu.com.cn/upload/usericon/3.png
// @match https://www.luogu.com.cn/chat
// @match https://www.luogu.com.cn/chat/*
// @match https://www.luogu.com.cn/chat?uid=*
// @grant none
// ==/UserScript==
(function() {
'use strict';
let pendingFocus = false; // 标记是否需要在消息更新后聚焦
function getInputElement() {
let input = document.querySelector('textarea.lfe-form-sz-middle');
if (input && input.offsetParent !== null) return input;
const fallbackSelectors = [
'textarea[name="content"]',
'.chat-input textarea',
'.message-editor textarea',
'.input-wrap textarea',
'#chat-input textarea'
];
for (const sel of fallbackSelectors) {
const el = document.querySelector(sel);
if (el && el.offsetParent !== null) return el;
}
return null;
}
function isSearchInput(el) {
if (!el) return false;
if (el.placeholder && el.placeholder.includes('搜索联系人')) return true;
if (el.closest && el.closest('.side')) return true;
return false;
}
function focusInput(retries = 8) {
if (isSearchInput(document.activeElement)) return;
const input = getInputElement();
if (!input) {
if (retries > 0) setTimeout(() => focusInput(retries - 1), 100);
return;
}
if (document.activeElement === input) {
pendingFocus = false;
return;
}
input.focus();
if (input.isContentEditable) {
const range = document.createRange();
const sel = window.getSelection();
range.selectNodeContents(input);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
// 检查是否聚焦成功,不成功则重试
setTimeout(() => {
if (document.activeElement !== input) {
if (retries > 0) focusInput(retries - 1);
} else {
pendingFocus = false;
}
}, 100);
}
// Ctrl+Enter 触发时,设置待聚焦标记
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'Enter') {
const active = document.activeElement;
if (active && (active.tagName === 'TEXTAREA' || active.isContentEditable)) {
pendingFocus = true; // 标记需要聚焦
// 同时开启 MutationObserver 监听(如果尚未开启)
if (!observer) {
startObserver();
}
}
}
});
let observer = null;
function startObserver() {
observer = new MutationObserver((mutations) => {
if (!pendingFocus) return;
// 检查是否有消息列表变化
for (const mutation of mutations) {
if (mutation.type === 'childList' && mutation.addedNodes.length) {
// 延迟聚焦,给页面渲染时间
setTimeout(() => focusInput(8), 200);
// 一次变化后不必重复触发
pendingFocus = false;
// 可以停止观察,下次发送时再开启
if (observer) {
observer.disconnect();
observer = null;
}
break;
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
// 初始加载时若需要聚焦,也可以触发一次(可选)
window.addEventListener('load', () => {
// 不自动聚焦,除非用户操作
});
})();