DEV Community

Cover image for Adding custom keyboard shortcuts to any website
Muhammad Sifat Hossain
Muhammad Sifat Hossain

Posted on

Adding custom keyboard shortcuts to any website

Whenever I'm studying English, I always use the google translate website to lookup unknown words.

A screenshot of google translate page

But there is a problem! You see the two buttons marked red? As a hardcore VIM user, I hate to touch my mouse to click those 😩. But luckily Allah gave me the ability to program things.

There is a cool extension out there called User JavaScript and CSS that allows us to inject our own JavaScript and CSS code into any website.

Screenshot of the User JavaScript and CSS extension homepage in chrome webstore

At first, we've to select those button elements to click them programmatically. But they all have random classes and ids assigned to them, which are unreliable as selectors. After some searching, I've found that all the buttons have an attribute called aria-label.

For the two pronunciation buttons, the value of aria-label is "Listen to source text" and for the clear button it's "Clear source text".

We can write the following code snippet to select these buttons:

const clearBtn = document.querySelector('[aria-label="Clear source text"]');

const firstSpeakBtn = document.querySelectorAll(
  '[aria-label="Listen to source text"]'
)[1];
Enter fullscreen mode Exit fullscreen mode

Now, we can invoke the clearBtn.click() and firstSpeakBtn.click() methods to clear and pronounce the input text respectively.

Secondly, we need to setup an event listener for the keydown events so that we know when to execute clicks on those buttons.

const shortcuts = {};

window.addEventListener("keydown", (e) => {
  // If Control is not pressed or if the Control is pressed alone
  // then return and do nothing.
  if (!e.ctrlKey || e.key === "Control") return;

  const key = e.key;
  if (key in shortcuts) {
    // override browser keyboard shortcuts
    e.preventDefault();
    e.stopPropagation();

    // take some action here
  }
});
Enter fullscreen mode Exit fullscreen mode

I want the Ctrl-p to pronounce and Ctrl-l to clear the input text.

Update:

Added Ctrl-k and Ctrl-j for scrolling up and down respectively.

Here is the full code:

// Ctrl-l = clear the input in the first box
// Ctrl-p = pronounce the text in the first box
// Ctrl-j = scroll down
// Ctrl-k = scroll up
const shortcuts = Object.freeze({
  p: () => getSpeakButton().click(),
  l: () => getClearButton().click(),
  j: () => scrollBy({ top: 100, left: 0, behavior: "smooth" }),
  k: () => scrollBy({ top: -100, left: 0, behavior: "smooth" }),
});

window.addEventListener("keydown", (e) => {
  // If Control is not pressed or if the Control is pressed alone
  // then return and do nothing.
  if (!e.ctrlKey || e.key === "Control") return;

  const key = e.key;
  if (key in shortcuts) {
    // override browser keyboard shortcuts
    e.preventDefault();
    e.stopPropagation();

    shortcuts[key]();
  }
});

function getClearButton() {
  const clearBtn = document.querySelector('[aria-label="Clear source text"]');
  return makeBtnSafeToClick(clearBtn);
}

function getSpeakButton() {
  const firstSpeakBtn = document.querySelectorAll(
    '[aria-label="Listen to source text"]'
  )[1];
  return makeBtnSafeToClick(firstSpeakBtn);
}

/*
 * If the button is `nullish`, make sure that invoking the `.click()` method
 * doesn't throw an error.
 * */
function makeBtnSafeToClick(btn) {
  return btn ? btn : { click: () => {} };
}
Enter fullscreen mode Exit fullscreen mode

Now, go to the google translate website and click on the User JavaScript and CSS extension and you should see a modal like this:

A modal dialog with add new button

then click on the Add new button and it'll take you to a page like this:

Editor Page

Finally, copy the full code snippet from above and paste it into the JS tab and click Save then reload the page.

At last, we can stay away from that nasty mouse! Life is gud 😋.

Credits

The cover image is taken from Unsplash

Top comments (0)