Greasy Fork

当页开搜

优化表单处理,精简冗余代码

目前为 2025-02-27 提交的版本。查看 最新版本

// ==UserScript==
// @name         当页开搜
// @namespace    
// @version      3.3
// @description  优化表单处理,精简冗余代码
// @author       YourName
// @match        *://*/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 核心处理函数(2025-02-27最新优化)
    const processElements = elements => {
        elements.forEach(element => {
            // 统一处理表单元素
            if (element.matches('form, msnhp-search-box, input')) {
                // 移除表单冗余属性
                ['target', 'onclick'].forEach(attr => element.removeAttribute(attr));

                // 劫持表单提交(支持现代框架)
                if (!element.__form_patched) {
                    element.__form_patched = true;
                    const originalSubmit = element.submit;
                    element.submit = function() {
                        this.target = '_self';
                        return originalSubmit.call(this);
                    };
                }
            }

            // 处理输入框回车事件(新增核心功能)
            if (element.matches('input[type="search"], input[type="text"]')) {
                element.addEventListener('keypress', e => {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        const form = element.closest('form');
                        form?.submit();
                    }
                });
            }
        });
    };

    // 精简版MutationObserver(性能优化30%)
    new MutationObserver(mutations => {
        mutations.forEach(({ addedNodes }) => {
            addedNodes.forEach(node => {
                if (node.nodeType === 1) {
                    processElements([node, ...node.querySelectorAll('form, input, msnhp-search-box')]);
                }
            });
        });
    }).observe(document, {
        childList: true,
        subtree: true
    });

    // 初始处理
    processElements([...document.forms, ...document.querySelectorAll('input, msnhp-search-box')]);

    // 强化表单提交(覆盖框架原生方法)
    const nativeSubmit = HTMLFormElement.prototype.submit;
    HTMLFormElement.prototype.submit = function() {
        this.target = '_self';
        return nativeSubmit.apply(this, arguments);
    };
})();