i need a tampermonkey script to change string contain ی and ک to ي and ك in input field. + change number persian or arabic to english number
Assistant
User
and optimize it?
Assistant
User
not work at all? why?
Assistant
User
Assistant
Sure! Below is a Tampermonkey script that will replace Persian characters ی and ک with their Arabic counterparts ي and ك respectively, in all input fields and textareas on the page. It will also convert Persian/Arabic digits ۰۱۲۳۴۵۶۷۸۹ and Arabic-Indic digits ٠١٢٣٤٥٦٧٨٩ to English digits 0123456789.
This script listens to input events and updates the field value accordingly.
javascript
// ==UserScript==
// @name Persian to Arabic Characters and Digit Converter
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Convert ی, ک to ي, ك and Persian/Arabic digits to English digits in input fields
// @author Your Name
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Mapping function
function convertText(text) {
return text
// Replace Persian ی (U+06CC) with Arabic ي (U+064A)
.replace(/\u06cc/g, '\u064a')
// Replace Persian ک (U+06A9) with Arabic ك (U+0643)
.replace(/\u06a9/g, '\u0643')
// Replace Persian digits ۰۱۲۳۴۵۶۷۸۹ with 0123456789
.replace(/[۰]/g, '0')
.replace(/[۱]/g, '1')
.replace(/[۲]/g, '2')
.replace(/[۳]/g, '3')
.replace(/[۴]/g, '4')
.replace(/[۵]/g, '5')
.replace(/[۶]/g, '6')
.replace(/[۷]/g, '7')
.replace(/[۸]/g, '8')
.replace(/[۹]/g, '9')
// Replace Arabic-Indic digits ٠١٢٣٤٥٦٧٨٩ with 0123456789
.replace(/[٠]/g, '0')
.replace(/[١]/g, '1')
.replace(/[٢]/g, '2')
.replace(/[٣]/g, '3')
.replace(/[٤]/g, '4')
.replace(/[٥]/g, '5')
.replace(/[٦]/g, '6')
.replace(/[٧]/g, '7')
.replace(/[٨]/g, '8')
.replace(/[٩]/g, '9');
}
// Handle input event
function handleInput(event) {
const el = event.target;
const start = el.selectionStart;
const end = el.selectionEnd;
const converted = convertText(el.value);
if (el.value !== converted) {
el.value = converted;
// Attempt to restore cursor position, might jump if replaced characters differ in length
el.setSelectionRange(start, end);
}
}
function addListenersToElement(el) {
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
el.addEventListener('input', handleInput, false);
}
}
// Add listeners to existing input/textarea elements
document.querySelectorAll('input[type="text"], input:not([type]), textarea').forEach(addListenersToElement);
// Also listen for dynamically added inputs/textareas
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1) {
if (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA') {
addListenersToElement(node);
}
// Also check children in case inputs inside added container
node.querySelectorAll && node.querySelectorAll('input[type="text"], input:not([type]), textarea').forEach(addListenersToElement);
}
});
}
});
observer.observe(document.body, { childList: true, subtree: true });
})();
How to use:
Install Tampermonkey or a similar userscript manager in your browser.
Create a new script and paste the above code.
Save it and reload the page where you want this behavior.
When you type in inputs or textareas, the specified characters and digits will automatically convert.
Let me know if you want it working for contenteditable divs as well or any other modifications!
Certainly! Let's optimize the script for better performance and cleaner code:
Combine all digit replacements into a single .replace with a regex and lookup map.
Cache regex patterns and avoid multiple .replace calls.
Avoid resetting cursor position if nothing changed.
Use event delegation instead of attaching multiple event listeners (better for dynamically added inputs).
Keep MutationObserver only if needed, or rely on event delegation if possible.
Optimized version:
javascript
// ==UserScript==
// @name Perso-Arabic Character and Digit Converter - Optimized
// @namespace http://tampermonkey.net/
// @version 1.1
// @description Convert ی, ک to ي, ك and Persian/Arabic digits to English digits in input and textarea with event delegation and efficient replacement
// @author Your Name
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Map for digits replacement: Persian & Arabic-Indic digits to ASCII digits
const digitMap = {
'۰': '0','١': '1', '۱': '1',
'۲': '2','٢': '2',
'۳': '3','٣': '3',
'۴': '4','٤': '4',
'۵': '5','٥': '5',
'۶': '6','٦': '6',
'۷': '7','٧': '7',
'۸': '8','٨': '8',
'۹': '9','٩': '9',
'٠': '0'
};
// Regex: match ی(06CC), ک(06A9), Persian digits, Arabic-Indic digits, Arabic digits if any
const regex = /[\u06cc\u06a9۰-۹٠-٩]/g;
function convertText(text) {
return text.replace(regex, ch => {
if (ch === '\u06cc') return '\u064a'; // ی -> ي
if (ch === '\u06a9') return '\u0643'; // ک -> ك
return digitMap[ch] || ch;
});
}
function onInput(e) {
const el = e.target;
if (!((el.tagName === 'INPUT' && (el.type === 'text' || el.type === 'search' || el.type === 'tel' || el.type === 'url' || el.type === 'password' || el.type === 'email')) || el.tagName === 'TEXTAREA')) {
return; // Ignore other inputs like checkbox, number, etc.
}
const val = el.value;
const converted = convertText(val);
if (val !== converted) {
// Preserve cursor position relative to changes
const start = el.selectionStart;
const end = el.selectionEnd;
el.value = converted;
// Restore selection if possible
try {
el.setSelectionRange(start, end);
} catch {}
}
}
// Use event delegation: listen on document for input events
document.addEventListener('input', onInput, true);
})();
Key improvements:
Event delegation: A single listener on document handles all input fields and textareas, including dynamically added elements.
One regex + map lookup: Replaces multiple .replace() calls with one .replace() and a map/conditional inside.
Filter input types: Only text-like inputs are targeted to avoid interfering with inputs like checkbox or native numeric inputs.
Try/catch around cursor restore: Just in case setting selection fails (for example, during autocomplete or mobile quirks).
No MutationObserver needed: Event delegation inherently handles dynamic elements, so no MutationObserver overhead.
If you want it also to work on contenteditable, or if you have more requirements, just let me know!
Thanks for the feedback.
The optimized script should work, but there are a few reasons why it might fail depending on the page or browser environment:
Sometimes el.selectionStart / el.selectionEnd are null for input types or elements where cursor is not applicable (e.g., inputs with type=number or certain conditions).
Some inputs or frameworks block or interfere with scripts altering input values.
The event listener’s useCapture true (third argument), but maybe this event order conflicts with page script or something else.
Possibly incorrect input filtering.
Let's fix and verify step by step:
Test minimal working version without selection restoring, just to confirm the replacement happens.
Add debug logs to confirm events fire.
Simplify input filtering and test on basic input fields.
Minimal test version (with console logs):
javascript
// ==UserScript==
// @name Persian/Arabic to Arabic/Latin Conversion Test
// @namespace http://tampermonkey.net/
// @version 1.2
// @description Test conversion of ی, ک and digits on inputs/textareas
// @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'
};
const regex = /[\u06cc\u06a9۰-۹٠-٩]/g;
function convertText(text) {
return text.replace(regex, ch => {
if (ch === '\u06cc') return '\u064a'; // ی => ي
if (ch === '\u06a9') return '\u0643'; // ک => ك
return digitMap[ch] || ch;
});
}
function onInput(event) {
const el = event.target;
// Log input tag and type for debugging:
//console.log('Input event on:', el.tagName, el.type);
if (el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA') {
return;
}
// (Optional) skip input types where modifying raw value is bad:
// if(el.tagName === 'INPUT' && el.type && !['text', 'search', 'url', 'tel', 'password', 'email'].includes(el.type)) {
// return;
// }
const val = el.value;
const converted = convertText(val);
if (val !== converted) {
// For debugging:
//console.log('Before:', val, 'After:', converted);
el.value = converted;
// Restore cursor roughly at end
try {
let pos = el.selectionStart;
el.setSelectionRange(pos, pos);
} catch(e) {}
}
}
// Use capturing to get event early, but could use bubbling too
document.addEventListener('input', onInput, true);
})();
Please try this:
Paste it into Tampermonkey.
Open a simple page with a text input or textarea.
Type the Persian letter ی or ک or Persian digits like ۱۲۳ and check if converted live.
If still no effect:
Try the console:
js
document.addEventListener('input', e => console.log(e.target, e.target.value));
Verify your input event fires normally.
Check if another conflicting script may block value rewriting.
Why your original code might not work:
Possibly the input fields you test on are type=number (cursor/selection can't be set, or changing .value invalidates field).
Inputs may be inside iframes or shadow DOM, so event listener has no effect.
The use of setSelectionRange at incorrect positions can throw errors that prevent updates.
Using @match *://*/* generally covers all sites, but restrictive sites with CSP might block scripts.
Summary to fix your script:
Make sure you test on an <input type="text"> or <textarea> with simple HTML.
Remove strict input type filtering initially.
Log event to verify that handler triggers.
Gradually add cursor restore and filtering.
If you want, I can generate a step-by-step debugging version for you to find the issue! Would you like that?
Thanks for sharing the input element HTML — it reveals a few things:
It has type="text" → suitable for the script.
It has role="combobox" and aria-autocomplete="list" → likely part of a React-based autocomplete or select component, maybe controlled.
It has id="react-select-2-input", so it may be controlled or have synthetic events.
The value="" attribute is present in the HTML, but React (or framework) likely controls the input’s value via props/state, and directly changing .value might not persist or produce no visible change.
Problem diagnosis
React-controlled input fields often override .value directly — if you update .value from outside React, React might override back or not apply the actual change, so your changes are ignored or overwritten quickly.
Hence, your Tampermonkey script updates .value, but React's virtual DOM state is unaware of that change, causing it to revert immediately or ignore.
How to properly update React-controlled input values?
You generally need to:
Dispatch native input/change events so React detects the change.
Use React's internal event system or simulate events properly.
Or patch React’s internal state (which is fragile).
A robust approach
1. Use native input event input dispatch
After you update .value, you must dispatch an input event on the element that bubbles and is composed, so React picks the change up.
2. Use element selection preserving carefully
Combined with React, setting the cursor position can be tricky; do it carefully.
Updated Tampermonkey script for React-controlled inputs
javascript
// ==UserScript==
// @name Persian to Arabic and Digit Converter for React Inputs
// @namespace http://tampermonkey.net/
// @version 1.3
// @description Convert ی, ک to ي, ك and Persian/Arabic digits to English on React inputs/textareas, dispatch input event for React
// @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'
};
const regex = /[\u06cc\u06a9۰-۹٠-٩]/g;
function convertText(text) {
return text.replace(regex, ch => {
if (ch === '\u06cc') return '\u064a'; // ی => ي
if (ch === '\u06a9') return '\u0643'; // ک => ك
return digitMap[ch] || ch;
});
}
function triggerReactInputEvent(el) {
// React listens to a special synthetic event system, but triggering native events like this usually works:
const event = new Event('input', { bubbles: true, cancelable: true });
// For React 17 and older versions, you might also need to use,
// event.simulated = true; but usually not necessary
el.dispatchEvent(event);
}
function onInput(event) {
const el = event.target;
if (!(el.tagName === 'INPUT' || el.tagName === 'TEXTAREA')) return;
const val = el.value;
const converted = convertText(val);
if (val !== converted) {
// Save cursor positions:
const start = el.selectionStart;
const end = el.selectionEnd;
// Update value:
el.value = converted;
// Restore cursor (if still possible)
try {
el.setSelectionRange(start, end);
} catch {}
// Trigger React-controlled input event to notify React of change
triggerReactInputEvent(el);
}
}
// Use capturing phase to catch events before React
document.addEventListener('input', onInput, true);
})();
Why this helps:
We update .value directly.
Then dispatch a native 'input' event to cause React's internal onChange handlers to fire, picking up value changes.
Cursor selection is attempted to be preserved.
Listening on capturing phase to process input before React.
Further notes:
If you want to be extra robust (some React versions listen to change events too), you could dispatch a change event afterward.
Some React libraries might normalize input differently, but for most this approach works.
You can test this snippet and paste some Persian/k/digits and verify they are converted immediately.
If still no effect:
Verify you don’t have other JS libraries instantly overriding changes or inputs re-rendering every keystroke.
Check browser console for errors.
Use console logs inside onInput to verify the event fires.
If you want, I can help you build a debug version that logs the process and helps verify cursor, event dispatch etc. Just ask!