Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

i need a greasmonkey script to listen to input fileld and if 1. user type persian or…

  1. User

    i need a greasmonkey script to listen to input fileld and if

    1. user type persian or arabic number convert it to english number.
    2. user type string contain ی or ک change to ي and ك
  2. Assistant

    Certainly! Below is a Greasemonkey (or Tampermonkey) userscript that listens to all input fields on a page. It performs two tasks as you requested:

    1. Converts Persian/Arabic digits to English digits as the user types.
    2. Converts the Persian letters ی and ک to the Arabic letters ي and ك in the input.
    // ==UserScript==
    // @name         Persian/Arabic to English Number and Letter Converter
    // @namespace    http://tampermonkey.net/
    // @version      1.0
    // @description  Convert Persian/Arabic digits to English digits and replace ی,k with Arabic ي,ك in inputs while typing
    // @author       YourName
    // @match        *://*/*
    // @grant        none
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        // Mapping Persian and Arabic digits to English digits
        const digitMap = {
            '۰': '0', // Persian 0
            '۱': '1',
            '۲': '2',
            '۳': '3',
            '۴': '4',
            '۵': '5',
            '۶': '6',
            '۷': '7',
            '۸': '8',
            '۹': '9',
            '٠': '0', // Arabic 0
            '١': '1',
            '٢': '2',
            '٣': '3',
            '٤': '4',
            '٥': '5',
            '٦': '6',
            '٧': '7',
            '٨': '8',
            '٩': '9'
        };
    
        // Replace function for digits and specific letters
        function replacePersianArabic(text) {
            let result = '';
            for (let ch of text) {
                // Convert digits
                if (digitMap.hasOwnProperty(ch)) {
                    result += digitMap[ch];
                }
                // Convert ی to ي
                else if (ch === 'ی') {
                    result += 'ي';
                }
                // Convert ک to ك
                else if (ch === 'ک') {
                    result += 'ك';
                }
                else {
                    result += ch;
                }
            }
            return result;
        }
    
        // Listener function for input fields
        function onInputListener(event) {
            let input = event.target;
    
            // Save current selection start and end to restore after modification
            let start = input.selectionStart;
            let end = input.selectionEnd;
    
            let oldValue = input.value;
            let newValue = replacePersianArabic(oldValue);
    
            if (oldValue !== newValue) {
                // Replace the value
                input.value = newValue;
    
                // Try to restore the cursor position - adjusting if characters were replaced
                // Calculate difference in length - usually won't change length here, but safe to handle.
                let diff = newValue.length - oldValue.length;
    
                if (start !== null && end !== null) {
                    // Adjust start and end, but keep them within bounds
                    start += diff;
                    end += diff;
                    start = Math.min(newValue.length, Math.max(0, start));
                    end = Math.min(newValue.length, Math.max(0, end));
    
                    input.setSelectionRange(start, end);
                }
            }
        }
    
        // Listen to all current and future input[type="text"], textarea and inputs with contenteditable=true
        function addListenersToInputs() {
            let inputs = document.querySelectorAll('input[type="text"], textarea');
            inputs.forEach(input => {
                input.removeEventListener('input', onInputListener);
                input.addEventListener('input', onInputListener);
            });
        }
    
        // Observe the document for dynamically added input or textarea elements
        const observer = new MutationObserver(mutations => {
            let addedNodes = [];
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) { // Element node
                        if (node.matches('input[type="text"], textarea')) {
                            node.removeEventListener('input', onInputListener);
                            node.addEventListener('input', onInputListener);
                        }
                        // Also check descendants
                        node.querySelectorAll && node.querySelectorAll('input[type="text"], textarea').forEach(el => {
                            el.removeEventListener('input', onInputListener);
                            el.addEventListener('input', onInputListener);
                        });
                    }
                });
            });
        });
    
        // Start observing for added nodes inside body
        observer.observe(document.body, {childList: true, subtree: true});
    
        // Add listeners to existing inputs on page load
        window.addEventListener('load', addListenersToInputs);
        // Also run immediately in case script loads after DOM content is ready
        addListenersToInputs();
    
    })();
    

    How to use:

    1. Install Greasemonkey or Tampermonkey extension in your browser.
    2. Create a new userscript and paste the entire code above.
    3. Save and reload the page where you want this behavior.
    4. When you type Persian or Arabic digits, they automatically change to English digits.
    5. When you type ی or ک, they change to the Arabic ي and ك.

    Notes:

    • The script works on any text input or textarea fields.
    • It respects cursor position, attempting to keep caret in place as it modifies the value.
    • If you want to extend this to contenteditable fields or other inputs (like input[type=number]), let me know, I can adjust it.

    Let me know if you need customization or have issues!

  3. User

    in your code, numbers section is ok, but string contain ی and ک not work at all? why?

  4. Assistant

    Thank you for testing and pointing that out!

    The issue stems from the fact that in your input text the letters ی and ک might not exactly match the Unicode characters used in the code, or you may be entering a different form of those characters. Also, it could be a problem with the normalization or character codes.

    Let's verify:

    • The character ی (Persian Yeh) Unicode: U+06CC
    • The character ک (Persian Keheh) Unicode: U+06A9
    • You want to convert those to Arabic letters:
      • ي (Arabic Yeh) Unicode: U+064A
      • ك (Arabic Kaf) Unicode: U+0643

    In the code, I replaced 'ی' with 'ي' and 'ک' with 'ك'. This should work if the input text contains those exact characters.

    Possible reasons it doesn't work:

    1. The input text uses a different character that looks similar but is not the exact Unicode character.
    2. The input event is fired before the IME or input method fully commits the character, which may cause issues.
    3. The original routine doesn’t handle uppercase/lowercase or combined forms (though with these letters it's usually irrelevant).

    Quick test:

    Let's confirm the character codes at runtime.

    You can add this snippet inside the onInputListener to log character codes of each typed char:

    console.log('chars:', [...input.value].map(c => c + '(' + c.charCodeAt(0).toString(16) + ')').join(', '));
    

    Put that before replacePersianArabic call and inspect the console while typing the problematic letters to see if the input characters are exactly what you expect.


    Solution / Fix with normalization and improved replace function:

    To ensure that all forms of these characters are caught, you can normalize the input and also add a regex-based replace, which is usually better for this type of in-string replacements.

    Updated replacePersianArabic function:

    function replacePersianArabic(text) {
        // Replace digits:
        text = text.replace(/[۰-۹٠-٩]/g, ch => digitMap[ch] || ch);
        
        // Replace Persian ی (U+06CC) with Arabic ي (U+064A)
        // Replace Persian ک (U+06A9) with Arabic ك (U+0643)
        text = text.replace(/ی/g, 'ي').replace(/ک/g, 'ك');
        
        return text;
    }
    

    This approach uses regular expressions which are generally more reliable for replacements inside strings.


    What about the original iteration method vs regex?

    Previously you looped character by character. That is okay, but replacing in bulk with regex is simpler and often more fail-safe.


    Full updated script snippet:

    function replacePersianArabic(text) {
        text = text.replace(/[۰-۹٠-٩]/g, ch => digitMap[ch] || ch)
                   .replace(/ی/g, 'ي')
                   .replace(/ک/g, 'ك');
        return text;
    }
    

    Try this update and see if it resolves the problem.

    If you want, I can provide the entire updated userscript accordingly!

  5. User

    optimize below code and remove unnecessary part:

    // ==UserScript==
    // @name         Persian/Arabic to English Number and Letter Converter
    // @namespace    http://tampermonkey.net/
    // @version      1.0
    // @description  Convert Persian/Arabic digits to English digits and replace ی,k with Arabic ي,ك in inputs while typing
    // @author       YourName
    // @match        *://*/*
    // @grant        none
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        // Mapping Persian and Arabic digits to English digits
        const digitMap = {
            '۰': '0', // Persian 0
            '۱': '1',
            '۲': '2',
            '۳': '3',
            '۴': '4',
            '۵': '5',
            '۶': '6',
            '۷': '7',
            '۸': '8',
            '۹': '9',
            '٠': '0', // Arabic 0
            '١': '1',
            '٢': '2',
            '٣': '3',
            '٤': '4',
            '٥': '5',
            '٦': '6',
            '٧': '7',
            '٨': '8',
            '٩': '9'
        };
    
        // Replace function for digits and specific letters
     //   function replacePersianArabic(text) {
       //     let result = '';
    //        for (let ch of text) {
    //            // Convert digits
    //            if (digitMap.hasOwnProperty(ch)) {
    //                result += digitMap[ch];
    //            }
                // Convert ی to ي
    //            else if (ch === 'ی') {
    //                result += 'ي';
     //           }
                // Convert ک to ك
       //         else if (ch === 'ک') {
      //              result += 'ك';
     //           }
    //            else {
    //                result += ch;
    //            }
    //        }
    //        return result;
    //    }
      
      function replacePersianArabic(text) {
        text = text.replace(/[۰-۹٠-٩]/g, ch => digitMap[ch] || ch)
                   .replace(/ی/g, 'ي')
                   .replace(/ک/g, 'ك');
        return text;
    }
      
      
    
        // Listener function for input fields
        function onInputListener(event) {
            let input = event.target;
    
            // Save current selection start and end to restore after modification
            let start = input.selectionStart;
            let end = input.selectionEnd;
    
            let oldValue = input.value;
            let newValue = replacePersianArabic(oldValue);
    
            if (oldValue !== newValue) {
                // Replace the value
                input.value = newValue;
    
                // Try to restore the cursor position - adjusting if characters were replaced
                // Calculate difference in length - usually won't change length here, but safe to handle.
                let diff = newValue.length - oldValue.length;
    
                if (start !== null && end !== null) {
                    // Adjust start and end, but keep them within bounds
                    start += diff;
                    end += diff;
                    start = Math.min(newValue.length, Math.max(0, start));
                    end = Math.min(newValue.length, Math.max(0, end));
    
                    input.setSelectionRange(start, end);
                }
            }
        }
    
        // Listen to all current and future input[type="text"], textarea and inputs with contenteditable=true
        function addListenersToInputs() {
            let inputs = document.querySelectorAll('input[type="text"], textarea');
            inputs.forEach(input => {
                input.removeEventListener('input', onInputListener);
                input.addEventListener('input', onInputListener);
            });
        }
    
        // Observe the document for dynamically added input or textarea elements
        const observer = new MutationObserver(mutations => {
            let addedNodes = [];
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) { // Element node
                        if (node.matches('input[type="text"], textarea')) {
                            node.removeEventListener('input', onInputListener);
                            node.addEventListener('input', onInputListener);
                        }
                        // Also check descendants
                        node.querySelectorAll && node.querySelectorAll('input[type="text"], textarea').forEach(el => {
                            el.removeEventListener('input', onInputListener);
                            el.addEventListener('input', onInputListener);
                        });
                    }
                });
            });
        });
    
        // Start observing for added nodes inside body
        observer.observe(document.body, {childList: true, subtree: true});
    
        // Add listeners to existing inputs on page load
        window.addEventListener('load', addListenersToInputs);
        // Also run immediately in case script loads after DOM content is ready
        addListenersToInputs();
    
    })();
    
  6. Assistant

    Certainly! Here's the optimized, cleaned-up version of your script with unnecessary comments and duplicated logic removed, while keeping full functionality intact:

    // ==UserScript==
    // @name         Persian/Arabic to English Number and Letter Converter
    // @namespace    http://tampermonkey.net/
    // @version      1.1
    // @description  Convert Persian/Arabic digits to English digits and replace ی, ک with Arabic ي, ك in inputs while typing
    // @match        *://*/*
    // @grant        none
    // ==/UserScript==
    
    (function() {
        'use strict';
    
        const digitMap = {
            '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4',
            '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9',
            '٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4',
            '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9'
        };
    
        function replacePersianArabic(text) {
            return text
                .replace(/[۰-۹٠-٩]/g, ch => digitMap[ch] || ch)
                .replace(/ی/g, 'ي')
                .replace(/ک/g, 'ك');
        }
    
        function onInputListener(event) {
            const input = event.target;
            const oldValue = input.value;
            const newValue = replacePersianArabic(oldValue);
    
            if (oldValue !== newValue) {
                const start = input.selectionStart;
                const end = input.selectionEnd;
    
                input.value = newValue;
    
                // Restore cursor position (safe adjustment, length should remain unchanged here)
                if (start !== null && end !== null) {
                    input.setSelectionRange(start, end);
                }
            }
        }
    
        function addListenersToInputs(root = document) {
            root.querySelectorAll('input[type="text"], textarea').forEach(input => {
                input.removeEventListener('input', onInputListener);
                input.addEventListener('input', onInputListener);
            });
        }
    
        const observer = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                for (const node of mutation.addedNodes) {
                    if (node.nodeType === 1) { // Element node
                        if (node.matches('input[type="text"], textarea')) {
                            node.removeEventListener('input', onInputListener);
                            node.addEventListener('input', onInputListener);
                        }
                        addListenersToInputs(node);
                    }
                }
            }
        });
    
        observer.observe(document.body, { childList: true, subtree: true });
    
        // Add listeners to existing inputs as soon as possible
        addListenersToInputs();
    
        // Also add on window load in case elements appear late via scripts
        window.addEventListener('load', () => addListenersToInputs());
    })();
    

    Changes & optimizations:

    • Removed commented-out old code.
    • Simplified replacePersianArabic function to use chained .replace() calls.
    • Removed length difference calculation since input length doesn’t change here; the replaced chars have identical length.
    • Simplified addListenersToInputs to accept an optional root parameter for reuse on subtree nodes — avoids duplication.
    • Mutation observer now uses the reused addListenersToInputs(node) to add listeners to descendants of added nodes.
    • Removed unnecessary variables like addedNodes.
    • Improved formatting and comments for clarity.

    This script will efficiently listen to all existing and dynamically added inputs and textareas and perform the replacements you want as you type.

    Let me know if you want me to add support for contenteditable or other input types!