Focus input text field on Esc

Focus the first visible input text field when you press Esc key, or restore the previously focused element on second press

目前為 2016-03-11 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name          Focus input text field on Esc
// @description   Focus the first visible input text field when you press Esc key, or restore the previously focused element on second press
// @version       1.0.4
// @include       *
// @author        wOxxOm
// @namespace     wOxxOm.scripts
// @license       MIT License
// @run-at        document-start
// ==/UserScript==

var TEXT_FIELD = ' search text number url ';
var previousElement;
var first;

document.addEventListener('keydown', function(e) {
	if (e.keyCode != 27 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey)
		return;
	// find text inputs inside visible DOM containers
	var inputs = document.getElementsByTagName('input');
	for (var i=0, input, il=inputs.length; i<il && (input=inputs[i]); i++) {
		var priority = TEXT_FIELD.indexOf(' '+input.type+' ');
		if (priority >= 0) {
			var n=input, style;
			while (n && n.style && (style=getComputedStyle(n)) && style.display!='none' && style.visibility!='hidden')
				n = n.parentNode;
			if (!n || !n.style) {
				if (!first // set the first OR if it's empty, try to select an identically named input field with some text (happens on some sites)
						|| (input.value && input.name == first.name && (!input.form && !first.form || input.form.action == first.form.action))) {
					first = input;
					if (first.value)
						break;
				}
			}
		}
	}

	if (first) {
		if (first != document.activeElement) {
			// switch to the found input field
			previousElement = document.activeElement;
			onkeyup(function(){
				first.focus();
				first.select();
			});
		} else if (previousElement) {
			// restore focus to the element from which we jumped to an input field previously
			onkeyup(function(){
				document.activeElement.blur(); // in case document.body (page "background") was previously selected
				previousElement.focus();
			});
		}
	}

	// focusing should be done at key-up to prevent the Esc-keydown being also chain-handled by the just focused element
	function onkeyup(cb) {
		document.addEventListener('keyup', function keyup(e) {
			if (e.keyCode == 27) {
				document.removeEventListener('keyup', keyup);
				cb(e);
			}
		});
	}
});