Chrome - Remap keyboard inputs for specific sites (using Tampermonkey)
- Install "Tampermonkey" extension from Chrome webstore.
- In the website, click on the Tempermonkey icon to open the menu, then click on "Create a new script":
In this example, I will remap the "Esc" key to the "\" key. So whenever I press "\", it will send an "Esc" command to the webpage instead.
// ==UserScript==
// @name Remap key inputs
// @namespace http://tampermonkey.net/
// @version 2024-11-09
// @description try to take over the world!
// @author You
// @match https://yourtargetwebsite.com/path/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=yourtargetwebsite.com
// @grant none
// ==/UserScript==
function invokeEscKey() {
window.dispatchEvent(
new KeyboardEvent("keydown", {
altKey: false,
code: "Escape",
ctrlKey: false,
isComposing: false,
key: "Escape",
location: 0,
metaKey: false,
repeat: false,
shiftKey: false,
which: 27,
charCode: 0,
keyCode: 27,
})
);
}
(function() {
'use strict';
console.log("=========Tempermonkey script started!==========");
document.onkeypress = function (e) {
e = e || window.event;
if (e.key === '\\')
{
invokeEscKey();
}
};
})();
// EXAMPLE:
(Dailydiction.com)
function sendEnterKey(element){
const e = new KeyboardEvent('keydown', {
altKey: false,
key: 'Enter',
code: 'Enter',
ctrlKey: false,
isComposing: false,
which: 13,
charCode: 0,
keyCode: 13,
location: 0,
metaKey: false,
repeat: false,
shiftKey: false,
});
element.dispatchEvent(e);
}
function playAudio() {
const audio = document.getElementsByTagName('audio')[0];
if (audio && audio.paused) {
audio.play();
}
}
(function() {
'use strict';
console.log("=========Tempermonkey script started!==========");
document.onkeypress = function (e) {
e = e || window.event;
if (e.key === '\\')
{
// enter the current sentence into the textarea and press Enter
if (window.appGlobals)
{
const index = document.getElementById("btn-arrow-left").nextSibling.children[0].innerText;
const sentence = appGlobals.challenges.find(x => x.position == index).content;
const textarea = document.getElementsByTagName('textarea')[0];
textarea.value = sentence;
const audio = document.getElementsByTagName('audio')[0];
playAudio();
setTimeout(() => {
//remove the redundant character '\' at the end
textarea.value = sentence;
//click "Check" button
const checkButton = document.getElementById("btn-check");
checkButton.click()
},100);
}
}
};
})();
No comments: