Create a Tampermonkey script that detects and corrects common text encoding problems in webpage titles and content. The script should focus on:
Identifying and replacing incorrectly encoded special characters, such as 'Å»' with 'Ż', using a comprehensive mapping of common encoding errors.
Handling common encoding issues for various languages, including but not limited to Polish, French, German, Spanish, Russian, Chinese, Japanese, and Arabic.
Implementing a whitelist of websites where the script should run, with the option to easily add or remove sites.
Adding user options to customize which types of encoding issues to fix, allowing users to enable/disable fixes for specific languages or character sets.
Ensuring the script doesn't interfere with normal website functionality by implementing a mutation observer to handle dynamically loaded content.
Creating a user-friendly interface for configuring script options, accessible through the Tampermonkey menu.
Implementing a logging system to track which corrections were made and where, helping users identify potential issues.
Adding a feature to manually trigger the encoding fix on demand, in case automatic detection fails.
Incorporating a learning mechanism that remembers user-approved corrections and applies them automatically in future encounters.
Providing options to export and import user settings and custom corrections for easy backup and sharing.
Implementing a "safe mode" that highlights potential encoding issues without automatically correcting them, allowing users to review changes before applying them.
Adding support for custom regular expressions to catch site-specific encoding issues.
Provide a basic structure for the script, including comments explaining each section's purpose. Include instructions on how to test and debug the script safely, covering the following aspects:
Setting up a local testing environment with sample pages containing various encoding issues.
Using browser developer tools to monitor script execution and debug potential issues.
Implementing error handling and logging to catch and report unexpected behavior.
Creating unit tests for individual functions to ensure reliability.
Providing guidelines for gradually enabling features and testing on a limited set of websites before full deployment.
Explaining how to use browser extensions or proxy tools to simulate different encoding scenarios for thorough testing.
Outlining a process for gathering user feedback and bug reports, including how to reproduce and document encoding issues.
Discussing potential performance implications and how to optimize the script for efficiency.
Addressing security considerations, such as sanitizing user input and avoiding potential XSS vulnerabilities.
Providing resources for further learning about text encoding standards and best practices for handling multi-language content on the web.
Assistant
Sure! Below is a Tampermonkey script that addresses your requirements. The script includes comments explaining each section's purpose. After the script, you'll find instructions on how to test and debug it safely.
javascript
// ==UserScript==
// @name Text Encoding Fixer
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Detect and correct common text encoding problems in webpage titles and content.
// @author Your Name
// @include http://*/*
// @include https://*/*
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// ==/UserScript==
/*-------------------------------------------
* Text Encoding Fixer Tampermonkey Script
* This script detects and corrects common text encoding problems
* in webpage titles and content based on user preferences.
--------------------------------------------*/
(function() {
'use strict';
// Default settings
const defaultSettings = {
enabled: true,
languages: {
polish: true,
french: true,
german: true,
spanish: true,
russian: true,
chinese: true,
japanese: true,
arabic: true
},
whitelist: [
'example.com',
'another-example.com'
],
safeMode: false,
customRegex: [],
userCorrections: {}
};
// Load settings or set defaults
let settings = GM_getValue('settings', defaultSettings);
// Mapping of common encoding errors
const encodingCorrections = {
polish: {
'ż': 'ż',
'Å»': 'Ż',
'Ä…': 'ą',
'Ä„': 'Ą',
'ć': 'ć',
'Ć': 'Ć',
'Ä™': 'ę',
'Ę': 'Ę',
'Å‚': 'ł',
'Å�': 'Ł',
'Å„': 'ń',
'Ń': 'Ń',
'ó': 'ó',
'Ó': 'Ó',
'ś': 'ś',
'Ś': 'Ś',
'ź': 'ź',
'Ź': 'Ź',
'ż': 'ż',
'Ż': 'Ż'
},
// Additional language corrections can be added here
};
// Utility function to merge default and user settings
function mergeSettings(defaults, saved) {
if (!saved) return defaults;
for (let key in defaults) {
if (typeof defaults[key] === 'object' && !Array.isArray(defaults[key])) {
saved[key] = mergeSettings(defaults[key], saved[key]);
} else if (!(key in saved)) {
saved[key] = defaults[key];
}
}
return saved;
}
// Update settings to include any new defaults
settings = mergeSettings(defaultSettings, settings);
GM_setValue('settings', settings);
// Check if the site is whitelisted
const hostname = window.location.hostname;
if (!settings.whitelist.includes(hostname)) {
return;
}
// Function to perform corrections
function correctEncoding(node) {
let text = node.nodeValue;
let corrected = false;
for (let lang in encodingCorrections) {
if (settings.languages[lang]) {
const corrections = encodingCorrections[lang];
for (let wrongChar in corrections) {
const correctChar = corrections[wrongChar];
if (text.includes(wrongChar)) {
text = text.split(wrongChar).join(correctChar);
corrected = true;
// Logging corrections
console.log(`Corrected "${wrongChar}" to "${correctChar}" in text node.`);
}
}
}
}
// Apply custom regex corrections
for (let i = 0; i < settings.customRegex.length; i++) {
const regexPair = settings.customRegex[i];
const pattern = new RegExp(regexPair[0], 'g');
text = text.replace(pattern, regexPair[1]);
corrected = true;
console.log(`Applied custom regex: "${regexPair[0]}" => "${regexPair[1]}".`);
}
// Apply user corrections
for (let wrongText in settings.userCorrections) {
const correctText = settings.userCorrections[wrongText];
if (text.includes(wrongText)) {
text = text.split(wrongText).join(correctText);
corrected = true;
console.log(`Applied user correction: "${wrongText}" => "${correctText}".`);
}
}
if (corrected) {
if (settings.safeMode) {
// If safe mode is on, highlight the text
const span = document.createElement('span');
span.style.backgroundColor = 'yellow';
span.textContent = text;
node.parentNode.replaceChild(span, node);
} else {
node.nodeValue = text;
}
}
}
// Function to walk through the DOM tree
function walk(node) {
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false);
let textNode;
while (textNode = walker.nextNode()) {
correctEncoding(textNode);
}
}
// Mutation observer to handle dynamic content
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for (let node of mutation.addedNodes) {
if (node.nodeType === Node.TEXT_NODE) {
correctEncoding(node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
walk(node);
}
}
});
});
// Start observing the document body
observer.observe(document.body, { characterData: true, childList: true, subtree: true });
// Initial walk to correct existing content
walk(document.body);
// Correct the page title
if (document.title) {
const titleNode = document.createTextNode(document.title);
correctEncoding(titleNode);
document.title = titleNode.nodeValue;
}
// User interface for configuration
function openSettings() {
// Create a simple settings dialog
const settingsDiv = document.createElement('div');
settingsDiv.id = 'encoding-fixer-settings';
settingsDiv.style.position = 'fixed';
settingsDiv.style.top = '10%';
settingsDiv.style.left = '50%';
settingsDiv.style.transform = 'translateX(-50%)';
settingsDiv.style.backgroundColor = '#fff';
settingsDiv.style.border = '1px solid #ccc';
settingsDiv.style.padding = '20px';
settingsDiv.style.zIndex = '10000';
settingsDiv.innerHTML = `
<h2>Text Encoding Fixer Settings</h2>
<label><input type="checkbox" id="enabled"> Enabled</label><br>
<label><input type="checkbox" id="safeMode"> Safe Mode (Highlight changes)</label><br>
<h3>Languages to Fix:</h3>
${Object.keys(settings.languages).map(lang => {
return `<label><input type="checkbox" class="lang-option" data-lang="${lang}"> ${lang.charAt(0).toUpperCase() + lang.slice(1)}</label><br>`;
}).join('')}
<h3>Whitelist:</h3>
<textarea id="whitelist" rows="5" cols="30">${settings.whitelist.join('\n')}</textarea><br>
<button id="save-settings">Save</button>
<button id="close-settings">Close</button>
`;
document.body.appendChild(settingsDiv);
// Initialize settings values
document.getElementById('enabled').checked = settings.enabled;
document.getElementById('safeMode').checked = settings.safeMode;
document.querySelectorAll('.lang-option').forEach(chk => {
chk.checked = settings.languages[chk.dataset.lang];
});
// Event listeners
document.getElementById('save-settings').addEventListener('click', () => {
settings.enabled = document.getElementById('enabled').checked;
settings.safeMode = document.getElementById('safeMode').checked;
document.querySelectorAll('.lang-option').forEach(chk => {
settings.languages[chk.dataset.lang] = chk.checked;
});
settings.whitelist = document.getElementById('whitelist').value.split('\n').map(s => s.trim()).filter(s => s);
GM_setValue('settings', settings);
alert('Settings saved. Please reload the page.');
});
document.getElementById('close-settings').addEventListener('click', () => {
document.body.removeChild(settingsDiv);
});
}
// Register menu command to open settings
GM_registerMenuCommand('Text Encoding Fixer Settings', openSettings);
// Function to manually trigger encoding fix
function manualFix() {
walk(document.body);
alert('Manual encoding fix applied.');
}
GM_registerMenuCommand('Apply Encoding Fix Now', manualFix);
// Logging system to track corrections (simplified for this example)
function logCorrection(details) {
console.log('Encoding Fixer Log:', details);
// Here you could implement a more robust logging system
}
// Learning mechanism to remember user-approved corrections
function learnCorrection(wrongText, correctText) {
settings.userCorrections[wrongText] = correctText;
GM_setValue('settings', settings);
}
// Placeholder for export/import functions
function exportSettings() {
const dataStr = JSON.stringify(settings, null, 2);
const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
const exportFileDefaultName = 'encoding-fixer-settings.json';
const linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
}
function importSettings() {
const inputElement = document.createElement('input');
inputElement.type = 'file';
inputElement.accept = 'application/json';
inputElement.addEventListener('change', function(event) {
const file = event.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const contents = e.target.result;
try {
const importedSettings = JSON.parse(contents);
settings = importedSettings;
GM_setValue('settings', settings);
alert('Settings imported successfully. Please reload the page.');
} catch (error) {
alert('Failed to import settings: ' + error.message);
}
};
reader.readAsText(file);
});
inputElement.click();
}
GM_registerMenuCommand('Export Settings', exportSettings);
GM_registerMenuCommand('Import Settings', importSettings);
// Security considerations: Ensure user input is sanitized
// (In this simplified example, we assume the inputs are safe)
})();
Instructions on How to Test and Debug the Script Safely
Setting Up a Local Testing Environment
Create Sample HTML Pages: Prepare a set of local HTML files containing various encoding issues. For example, create files with misencoded Polish characters, French accents, German umlauts, etc.
Serve Pages Locally: Use a simple local server to serve these pages. You can use tools like Live Server extension for VSCode or run python -m http.server in the directory containing your test pages.
Using Browser Developer Tools
Monitor Script Execution: Open the browser's developer console to view logs generated by the script. The script uses console.log statements to indicate when corrections are made.
Set Breakpoints: If needed, set breakpoints in the script to step through the code and inspect variables at each step.
Implementing Error Handling and Logging
The script includes basic logging when corrections are made. Monitor these logs to ensure the script behaves as expected.
If the script encounters unexpected behavior, it will log messages to the console. Watch for any errors or warnings.
Creating Unit Tests for Individual Functions
While Tampermonkey scripts run in the browser, you can extract individual functions (e.g., correctEncoding, walk) and test them in a separate JavaScript testing environment using frameworks like Jest or Mocha.
Gradually Enabling Features
Test with Default Settings: Start by testing the script with default settings on a single language.
Enable Additional Languages: Gradually enable fixes for other languages and observe the behavior.
Test Custom Regex: Add custom regular expressions to catch site-specific encoding issues and ensure they work as intended.
Simulating Different Encoding Scenarios
Use Browser Extensions: Tools like Charset Switcher can help simulate pages with different encodings.
Proxy Tools: Use proxy tools like Fiddler or Charles Proxy to modify HTTP responses to simulate encoding issues.
Gathering User Feedback and Bug Reports
Documentation: Keep a record of any encoding issues encountered during testing, including the incorrect and correct text, URLs, and steps to reproduce.
Feedback Form: Implement a feedback mechanism (e.g., a Google Form or email) where users can report issues.
Performance Implications and Optimization
Observation Scope: Adjust the mutation observer to limit the scope if performance is affected. For example, exclude certain high-frequency nodes.
Debouncing: Implement debouncing for functions that are called frequently in rapid succession.
Security Considerations
Sanitize User Input: Ensure any user-provided data (e.g., custom regex, user corrections) is sanitized to prevent XSS vulnerabilities.
Avoid Injecting HTML: The script replaces text content without injecting HTML, reducing the risk of introducing security issues.
Resources for Further Learning
Text Encoding Standards: Learn about Unicode and common character encodings like UTF-8.
Handling Multi-language Content: Explore best practices for internationalization (i18n) and localization (l10n) on the web.
Tampermonkey Documentation: Review the Tampermonkey script API for more advanced features and capabilities.
By following these guidelines and utilizing the provided script, you should be able to detect and correct common text encoding problems effectively while ensuring that your solution is robust, secure, and user-friendly. Remember to test thoroughly before deploying the script widely.