corginyan / Spotify web hotkeys

// ==UserScript==
// @name     Spotify web hotkeys
// @include  https://open.spotify.com/*
// @version  0.0.2
// @license MIT
// ==/UserScript==

function getByXpath(xPath) {
    return document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
}

function pressNext() {
    let nextXPath = "//button[contains(concat(' ', normalize-space(@class), ' '), ' spoticon-skip-forward-')]"

    let keyNext = getByXpath(nextXPath)

    if (keyNext) {
        keyNext.click()
    }
}

function pressPrev() {
    let prevXPath = "//button[contains(concat(' ', normalize-space(@class), ' '), ' spoticon-skip-back-')]"

    let keyPrev = getByXpath(prevXPath)

    if (keyPrev) {
        keyPrev.click()
    }
}

function pressPlay() {
    let pauseXPath = "//button[contains(concat(' ', normalize-space(@class), ' '), ' spoticon-pause-')]"
    let playXPath = "//button[contains(concat(' ', normalize-space(@class), ' '), ' spoticon-play-')]"

    let pauseKey = getByXpath(pauseXPath)

    if (pauseKey) {
        pauseKey.click()
        return
    }

    let playKey = getByXpath(playXPath)

    if (playKey) {
        playKey.click()
    }
}

function isSearchBoxFocused() {
    let active = document.activeElement

    if (!active) {
        return
    }

    let search = document.getElementsByClassName("SearchInputBox__input")[0]

    if (!search) {
        return
    }

    return active === search
}

function handler(e) {
    if (isSearchBoxFocused()) {
        return
    }

    if (e.code === "KeyA") {
        pressPrev()
    } else if (e.code === "KeyD") {
        pressNext()
    } else if (e.code === "KeyS") {
        pressPlay()
    }
}

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