app.element.io - close a chat view

Close a chat view by pressing the ESC key

// ==UserScript==
// @name        app.element.io - close a chat view
// @namespace   https://app.element.io/
// @version     0.1
// @encoding    utf-8
// @description Close a chat view by pressing the ESC key
// @license     GPL-3.0-or-later
// @icon        https://raw.githubusercontent.com/vector-im/element-web/d1f7b0898acc670a0d7f611cfb072e9f57aa549d/res/vector-icons/favicon.ico
// @author      Denis Drakhnia ([email protected])
// @grant       none
// @match       https://app.element.io/*
// @inject-into content
// ==/UserScript==

var menu = null;
var staticDialog = null;
var dialog = null;

function handler(event) {
  if (event.code != "Escape") {
    return;
  }

  if (!menu) {
    menu = document.querySelector("div#mx_ContextualMenu_Container");
  }
  if (!staticDialog) {
    staticDialog = document.querySelector("div#mx_Dialog_StaticContainer");
  }
  if (!dialog) {
    dialog = document.querySelector("div#mx_Dialog_Container");
  }

  // Close the chat view.
  if (!(menu && menu.hasChildNodes()) &&
        !(staticDialog && staticDialog.hasChildNodes()) &&
        !(dialog && dialog.hasChildNodes())) {
    window.location.href = "/#/home";
    return;
  }

  // Or close the search box.
  if (staticDialog) {
    const bg = staticDialog.querySelector("div > div.mx_Dialog_background");
    if (bg) {
      bg.click();
      return;
    }
  }

  // Or close the create a room dialog.
  if (dialog) {
    const bg = dialog.querySelector("div > div.mx_Dialog_background");
    if (bg) {
      bg.click();
      return;
    }
  }
}

document.addEventListener("keydown", handler, true);