Skip to content

Instantly share code, notes, and snippets.

@qb20nh
Created December 6, 2019 04:57
Show Gist options
  • Save qb20nh/206971b325e078c78cf03cf13d9a0a69 to your computer and use it in GitHub Desktop.
Save qb20nh/206971b325e078c78cf03cf13d9a0a69 to your computer and use it in GitHub Desktop.
Search Anywhere
// ==UserScript==
// @name Search Anywhere
// @namespace http://tampermonkey.net/
// @version INITIAL
// @description Press Alt+D to activate search function within a webpage, Press Alt+D,D(Double Tap) for default browser behavior.
// @author tez
// @include http://*/*
// @include https://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
var main = (function() {
var isActive = false;
var searchElementQueries = ['[type="search"]', '[name*="search"]', '[id*="search"]', '[placeholder*=search]', '[name*="Search"]', '[id*="Search"]', '[placeholder*=Search]', '[name*="query"]', '[name*="Query"]', '[id*="query"]', '[id*="Query"]', '[name=q]', '[class*=search]', '[class*=Search]', '[name*=keyword]', '[name*=Keyword]'];
function focusSearchBar() {
var searchBarElement;
function focusCaretEnd(el) {
el.selectionStart = el.selectionEnd = el.value.length;
}
var candidate;
var currWidth = 0;
var maxWidth = 0;
for (var query of searchElementQueries) {
candidate = document.querySelector('input'+query);
if (candidate) {
currWidth = candidate.getBoundingClientRect().width
if (currWidth > maxWidth) {
maxWidth = currWidth;
searchBarElement = candidate;
}
}
}
if (searchBarElement && maxWidth > 0) {
searchBarElement.focus();
setTimeout(focusCaretEnd, 0, searchBarElement);
}
return !!searchBarElement;
}
function rightKeysPressed(e) {
return e.altKey && e.key == 'd';
}
function eventHandler(e) {
if (isActive = rightKeysPressed(e) && !isActive) {
if (focusSearchBar()) {
e.preventDefault();
e.stopPropagation();
}
}
}
function registerEvent() {
document.onkeydown = eventHandler;
document.onkeyup = function(e) {
isActive = rightKeysPressed(e);
};
}
return registerEvent;
})();
document.addEventListener('DOMContentLoaded', main);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment