// ==UserScript==
// @name Replace X.com URLs with Twitter.com URLs
// @namespace http://tampermonkey.net/
// @description Replaces URLs containing "https://twitter.com" or "https://twitter.com" with "https://twitter.com".
// @author Author Name
// @version 1.0
// @match https://www.thecoli.com/threads/*
// @match https://thecoli.com/threads/*
// @match https://xenforo.com/community/forums/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Function to get the current cursor position in a text input field
function getCursorPosition(input) {
let position = 0;
if ('selectionStart' in input) {
position = input.selectionStart;
} else if (document.selection) {
input.focus();
let selection = document.selection.createRange();
selection.moveStart('character', -input.value.length);
position = selection.text.length;
}
return position;
}
// Function to set the cursor position in a text input field
function setCursorPosition(input, position) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(position, position);
} else if (input.createTextRange) {
let range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', position);
range.moveStart('character', position);
range.select();
}
}
// Function to replace URLs in text input fields
function replaceURLs(event) {
// Get all editable fields on the page
let editableFields = document.querySelectorAll('[contenteditable="true"], .fr-element.fr-view.fr-element-scroll-visible');
// Get the target element of the event
let target = event.target;
// Check if the target is a text input field or an editable field
if (target.matches('textarea.input') || editableFields.includes(target)) {
// Save the current cursor position
let cursorPosition = getCursorPosition(target);
// Replace URLs in the value or innerHTML of the target element
let lines = target.value ? target.value.split('\n') : target.innerHTML.split('\n');
for (let i = 0; i < lines.length; i++) {
lines[i] = lines[i].replace(/https:\/\/(www\.)?x\.com/g, 'https://twitter.com');
if (i === cursorPosition.line) {
cursorPosition.column = lines[i].length;
}
}
target.value ? target.value = lines.join('\n') : target.innerHTML = lines.join('\n');
// Restore the cursor position
setCursorPosition(target, cursorPosition);
}
}
// Function to prevent cursor movement by arrow keys
// function preventCursorMovement(event) {
// Check if the key pressed is left or right arrow
// if (event.keyCode == 37 || event.keyCode == 39) {
// Prevent the default behavior of the key
event.preventDefault();
// }
// }
// Add event listeners for input and keydown events on the document
document.addEventListener('input', replaceURLs);
// document.addEventListener('keydown', preventCursorMovement);
})();