Skip to content

Instantly share code, notes, and snippets.

@yoogottamk
Created September 16, 2021 02:57
Show Gist options
  • Save yoogottamk/8ac0f21080a407a16f7ac649cff9ce74 to your computer and use it in GitHub Desktop.
Save yoogottamk/8ac0f21080a407a16f7ac649cff9ce74 to your computer and use it in GitHub Desktop.
WhatsApp web reply using keyboard
// ==UserScript==
// @name whatsapp-web-reply
// @namespace https://yoogottamk.github.io/
// @version 0.1
// @description reply to messages using keyboard shortcuts alt+{up,down}
// @author yoogottamk
// @match https://web.whatsapp.com/
// @grant none
// ==/UserScript==
(function () {
'use strict';
const getMessages = () => document.querySelectorAll(".message-in, .message-out"),
getDoubleClickEvent = () => {
let clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent('dblclick', true, true);
return clickEvent;
},
getMessageIdFromDOMAttributes = messageNode => messageNode.dataset.id.split("_")[2],
selectRelativeMessage = relativeDistance => () => {
const messageList = getMessages(),
messageIds = Array.from(messageList).map(getMessageIdFromDOMAttributes),
newMessageIndex = messageIds.findIndex(mId => mId == lastSelectedMessageId) + relativeDistance;
let selectedMessage;
if (!lastSelectedMessageId || newMessageIndex < 0 || newMessageIndex >= messageList.length)
selectedMessage = messageList[messageList.length - 1];
else
selectedMessage = messageList[newMessageIndex];
lastSelectedMessageId = getMessageIdFromDOMAttributes(selectedMessage);
selectedMessage.dispatchEvent(getDoubleClickEvent());
selectedMessage.scrollIntoView();
},
selectPreviousMessage = selectRelativeMessage(-1),
selectNextMessage = selectRelativeMessage(1);
let lastSelectedMessageId;
document.addEventListener("keydown", e => {
// 38 is up, 40 is down
if (e.keyCode == 38 && e.altKey) {
selectPreviousMessage();
e.stopPropagation();
} else if (e.keyCode == 40 && e.altKey) {
selectNextMessage();
e.stopPropagation();
}
// escape
if (e.keyCode == 27) {
lastSelectedMessageId = null;
}
}, true);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment