Open links easily using only the keyboard
当前为
// ==UserScript==
// @name Easy Keyboard Link Opener
// @description Open links easily using only the keyboard
// @version 0.13
// @namespace https://greasyfork.org/en/users/55535-sllypper
// @author sllypper
// @match *://*/*
// @grant none
// @todo add TAB to cycle between links
// ==/UserScript==
(function() {
'use strict';
// on the American keyboard layout, switch it to "`" instead
// or whatever other key you want
const HOTKEY = "'"
// allow or deny links that start with #
const ALLOW_ANCHOR_LINKS = true
let isSet = false;
let visibleLinks = [];
let page;
const tooltipColor = "#fff"
const tooltipBgColor = "#555"
function setHot() {
document.addEventListener("keydown", event => {
if (!isSet) {
if (event.key === HOTKEY && event.ctrlKey) {
actionHot();
}
} else {
if (event.key >= 0 && event.key < 10) {
let chosen
chosen = event.key === "0" ? visibleLinks[9] : visibleLinks[parseInt(event.key)-1]
window.location = chosen.getAttribute('href')
//console.log(chosen.getAttribute('href'))
}
/*else if (event.key === "Tab") {
}*/
//console.log(event.key)
clearAction()
}
})
}
function clearAction() {
let el
while (el = document.querySelector('.displayText_container')) el.remove()
visibleLinks = []
isSet = false
}
function actionHot() {
let links = Array.from(document.getElementsByTagName('a')).filter((el) => el.getAttribute('href') != null && !(el.offsetWidth === 0 || el.offsetHeight === 0) && isInViewport(el))
if (!ALLOW_ANCHOR_LINKS) links = links.filter((el) => el.getAttribute('href') != '#' )
let numlinks = 0
for (const el of links) {
visibleLinks.push(el)
if (numlinks >= 9) {
showTooltip(el, 0)
break;
}
numlinks += 1
showTooltip(el, numlinks)
}
isSet = true
}
function showTooltip(el, num) {
const superEl = document.createElement("span")
superEl.setAttribute('style','position: relative;')
superEl.setAttribute("class", "displayText_container")
let tooltip = document.createElement("span")
tooltip.setAttribute("class", "displayText")
tooltip.innerText = num
superEl.appendChild(tooltip)
el.appendChild(superEl)
}
function addCustomCSS() {
let customStyles = document.createElement("style");
customStyles.setAttribute("type", "text/css");
let styles = ".displayText { position: absolute; bottom: 100%; left: 100%; margin-left: 0; width: initial; background-color: "+tooltipBgColor+"; color: "+tooltipColor+"; text-align: center; border-radius: 2px; padding: 0px 2px; margin-bottom: -20px; line-height: 20px; font-size: 14px; z-index: 9999; }"
customStyles.innerHTML = styles;
document.getElementsByTagName("head")[0].appendChild(customStyles);
}
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
addCustomCSS()
setHot()
})();