Google Translate - Switch Languages Hotkey

Makes tab a hotkey to swap languages.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         Google Translate - Switch Languages Hotkey
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Makes tab a hotkey to swap languages.
// @author       Meztihn
// @match        http*://translate.google.com/*
// @match        http*://translate.google.co.uk/*
// @match        http*://translate.google.ru/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const tabKeyCode = 'Tab';
    const sourceTextArea = document.getElementById('source')
    const swapLanguagesButton = document.getElementById('gt-swap');

    sourceTextArea.addEventListener('keydown', onKeyDown, { capture: true });

    function onKeyDown(event) {
        if (event.code === tabKeyCode) {
            swapLanguages();
            event.preventDefault(); // prevents active element change and thus focus lose
        }
    }

    function swapLanguages() {
        click(swapLanguagesButton);

        // Standard click() doesn't work
        function click(button) {
            button.dispatchEvent(new MouseEvent('mouseover'));
            button.dispatchEvent(new MouseEvent('mousedown'));
            button.dispatchEvent(new MouseEvent('mouseup'));
        }
    }
})();