Highlight selected text

Press 'H' to highlight selected text. Press 'H' again on highlighted text to remove it.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

ستحتاج إلى تثبيت إضافة مثل Stylus لتثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتتمكن من تثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتثبيت هذا النمط.

ستحتاج إلى تثبيت إضافة لإدارة أنماط المستخدم لتثبيت هذا النمط.

(لدي بالفعل مثبت أنماط للمستخدم، دعني أقم بتثبيته!)

// ==UserScript==
// @name         Highlight selected text
// @namespace    https://greasyfork.org
// @version      1.0
// @description  Press 'H' to highlight selected text. Press 'H' again on highlighted text to remove it.
// @author       Bui Quoc Dung
// @match        *://*/*
// @grant        GM_addStyle
// ==/UserScript==

(function() {
    'use strict';

    GM_addStyle(`
        mark.userscript-highlight {
            background-color: #fff59d !important;
            color: black !important;
        }
    `);

    document.addEventListener('keydown', function(e) {
        if (e.key.toLowerCase() !== 'h') return;
        if (e.target.isContentEditable || ['INPUT', 'TEXTAREA'].includes(e.target.tagName)) return;

        const selection = window.getSelection();
        if (!selection.rangeCount || selection.isCollapsed) return;

        e.preventDefault();
        const range = selection.getRangeAt(0);
        const existingMark = range.commonAncestorContainer.parentElement.closest('mark.userscript-highlight');

        if (existingMark) {
            const parent = existingMark.parentNode;
            while (existingMark.firstChild) {
                parent.insertBefore(existingMark.firstChild, existingMark);
            }
            parent.removeChild(existingMark);
            parent.normalize();
        } else {
            const mark = document.createElement("mark");
            mark.className = 'userscript-highlight';

            try {
                range.surroundContents(mark);
            } catch (error) {
                console.error("Highlighting failed", error);
                alert("Unable to highlight this selection. Please try selecting a simpler text region.");
            }
        }

        selection.removeAllRanges();
    });
})();