Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Create a Tampermonkey script that detects and corrects common text encoding problems in…

  1. User

    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 'Ż'. Handling common encoding issues for various languages, including but not limited to Polish, French, German, and Spanish. Implementing a whitelist of websites where the script should run. Adding user options to customize which types of encoding issues to fix. Ensuring the script doesn't interfere with normal website functionality. 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.

  2. Assistant
    // ==UserScript==
    // @name         Encoding Fixer
    // @namespace    http://tampermonkey.net/
    // @version      1.0
    // @description  Detect and correct common text encoding problems in webpage titles and content
    // @author       
    // @match        https://www.example.com/*
    // @match        https://www.anotherexample.com/*
    // @grant        GM_registerMenuCommand
    // ==/UserScript==
    
    /*
    This Tampermonkey script detects and corrects common text encoding problems in webpage titles and content.
    It focuses on incorrectly encoded special characters for multiple languages.
    Users can customize which types of encoding issues to fix via the Tampermonkey menu commands.
    */
    
    // IIFE - Immediately Invoked Function Expression to avoid polluting the global namespace
    (function () {
        'use strict';
    
        // ==User Settings==
        /*
        This section defines user settings for which languages' encoding issues to fix.
        Users can toggle these settings via the Tampermonkey menu.
        */
        var settings = {
            'polish': true,
            'french': true,
            'german': true,
            'spanish': true
        };
    
        // ==Menu Commands==
        /*
        Register menu commands in Tampermonkey so the user can toggle language fixes on or off.
        */
        function registerMenu() {
            GM_registerMenuCommand("Toggle Polish Fixes (" + (settings['polish'] ? "On" : "Off") + ")", function () {
                settings['polish'] = !settings['polish'];
                alert('Polish Fixes ' + (settings['polish'] ? 'Enabled' : 'Disabled'));
                processPage();
            });
    
            GM_registerMenuCommand("Toggle French Fixes (" + (settings['french'] ? "On" : "Off") + ")", function () {
                settings['french'] = !settings['french'];
                alert('French Fixes ' + (settings['french'] ? 'Enabled' : 'Disabled'));
                processPage();
            });
    
            GM_registerMenuCommand("Toggle German Fixes (" + (settings['german'] ? "On" : "Off") + ")", function () {
                settings['german'] = !settings['german'];
                alert('German Fixes ' + (settings['german'] ? 'Enabled' : 'Disabled'));
                processPage();
            });
    
            GM_registerMenuCommand("Toggle Spanish Fixes (" + (settings['spanish'] ? "On" : "Off") + ")", function () {
                settings['spanish'] = !settings['spanish'];
                alert('Spanish Fixes ' + (settings['spanish'] ? 'Enabled' : 'Disabled'));
                processPage();
            });
        }
    
        // ==Character Mappings==
        /*
        This section contains mappings of incorrectly encoded characters to their correct equivalents for each language.
        The mappings are only included if the user has enabled fixes for that language.
        */
        var mappings = {};
    
        if (settings['polish']) {
            mappings['polish'] = {
                'Ä…': 'ą',
                'ć': 'ć',
                'Ä™': 'ę',
                'Å‚': 'ł',
                'Å„': 'ń',
                'ó': 'ó',
                'Å›': 'ś',
                'ż': 'ż',
                'ź': 'ź',
                'Ä„': 'Ą',
                'Ć': 'Ć',
                'Ę': 'Ę',
                'Å�': 'Ł',
                'Ń': 'Ń',
                'Ó': 'Ó',
                'Åš': 'Ś',
                'Å»': 'Ż',
                'Ź': 'Ź'
            };
        }
    
        if (settings['french']) {
            mappings['french'] = {
                'Ã ': 'à',
                'â': 'â',
                'ç': 'ç',
                'è': 'è',
                'é': 'é',
                'ê': 'ê',
                'ë': 'ë',
                'î': 'î',
                'ï': 'ï',
                'ô': 'ô',
                'ù': 'ù',
                'û': 'û',
                'ü': 'ü',
                'Ü': 'Ü',
                'À': 'À',
                'Â': 'Â',
                'É': 'É',
                'Ê': 'Ê',
                'Ë': 'Ë',
                'ÃŽ': 'Î',
                'Ï': 'Ï',
                'Ô': 'Ô',
                'Û': 'Û'
            };
        }
    
        if (settings['german']) {
            mappings['german'] = {
                'ä': 'ä',
                'ö': 'ö',
                'ü': 'ü',
                'ß': 'ß',
                'Ä': 'Ä',
                'Ö': 'Ö',
                'Ü': 'Ü'
            };
        }
    
        if (settings['spanish']) {
            mappings['spanish'] = {
                'á': 'á',
                'é': 'é',
                'í': 'í',
                'ó': 'ó',
                'ú': 'ú',
                'ñ': 'ñ',
                'Á': 'Á',
                'É': 'É',
                'Í': 'Í',
                'Ó': 'Ó',
                'Ú': 'Ú',
                'Ñ': 'Ñ'
            };
        }
    
        /*
        Merge all enabled mappings into one object for simpler processing.
        */
        var totalMappings = {};
        for (var lang in mappings) {
            if (mappings.hasOwnProperty(lang)) {
                Object.assign(totalMappings, mappings[lang]);
            }
        }
    
        // ==Text Processing Functions==
        /*
        The fixText function replaces incorrectly encoded characters in a given text string.
        The walk function recursively traverses the DOM to find text nodes and applies the fixText function.
        */
        function fixText(text) {
            var regex = new RegExp(Object.keys(totalMappings).join("|"), "g");
            return text.replace(regex, function (matched) {
                return totalMappings[matched];
            });
        }
    
        function walk(node) {
            var child, next;
    
            switch (node.nodeType) {
                case 1: // Element nodes
                case 9: // Document nodes
                case 11: // Document fragment nodes
                    child = node.firstChild;
                    while (child) {
                        next = child.nextSibling;
                        walk(child);
                        child = next;
                    }
                    break;
                case 3: // Text nodes
                    var fixedText = fixText(node.nodeValue);
                    if (fixedText !== node.nodeValue) {
                        node.nodeValue = fixedText;
                    }
                    break;
            }
        }
    
        // ==Process Page Content==
        /*
        The processPage function applies the text fixes to the entire document body and the page title.
        */
        function processPage() {
            walk(document.body);
            // Also fix the page title
            document.title = fixText(document.title);
        }
    
        // ==Initialize Script==
        /*
        Registers the menu commands and processes the page when the script is first run.
        */
        registerMenu();
        processPage();
    })();
    
    /*
    Instructions on Testing and Debugging:
    
    1. **Install Tampermonkey Extension**: Ensure you have the Tampermonkey extension installed in your browser.
    
    2. **Create a New Script**: Open the Tampermonkey dashboard and create a new userscript. Paste the entire script above into the editor.
    
    3. **Modify the @match Directives**: Update the `@match` lines at the top of the script to include the websites where you want the script to run. For example:
       ```javascript
       // @match        https://www.yourwebsite.com/*
    
    1. Save the Script: Save the script within Tampermonkey.

    2. Test the Script:

      • Navigate to one of the websites specified in your @match rules.
      • Observe the webpage to see if incorrectly encoded characters have been corrected.
    3. Use Menu Commands:

      • Click on the Tampermonkey icon in your browser toolbar.
      • Find the "Encoding Fixer" script in the menu.
      • Use the provided options to toggle fixes for different languages on or off.
      • Refresh the page to see changes take effect.
    4. Debugging:

      • Open your browser's developer console to check for any errors or logs.
      • If the script isn't working as expected, ensure that the site URL matches the @match patterns.
      • You can add console.log statements within the script to output debugging information.
    5. Safety Precautions:

      • The script modifies text content only and does not interact with forms, authentication, or backend services.
      • Be cautious when running scripts on websites that handle sensitive information.
      • Review and understand the script before running it, especially if modifying or extending it.
    6. Disabling the Script:

      • If you encounter issues, you can disable the script by toggling it off in the Tampermonkey dashboard.

    By following these instructions, you can safely test and debug the script to ensure it meets your needs without interfering with normal website functionality.

    
    **Note**: Remember to replace the placeholder URLs in the `@match` directives with the actual websites where you want the script to run. The script is designed to be safe and only modifies text nodes, preventing interference with website functionalities.
    
    Feel free to customize the character mappings or add new ones for additional languages as needed.