content.ts: Fix pages autofocusing elements

Some pages manage to focus a hidden input field on page load. This puts
tridactyl in insert mode without the user being aware of it. This commit
actively protects users who set `allowautofocus` to "false" against
this.

Closes https://github.com/tridactyl/tridactyl/issues/1492
This commit is contained in:
glacambre 2019-05-27 00:40:58 +02:00
parent 028ec390df
commit fff155e142
No known key found for this signature in database
GPG key ID: B9625DB1767553AC

View file

@ -72,6 +72,47 @@ document.addEventListener("readystatechange", _ =>
getAllDocumentFrames().forEach(f => listen(f)),
)
// Prevent pages from automatically focusing elements on load
config.getAsync("allowautofocus").then(allowautofocus => {
if (allowautofocus === "true") {
return
}
const preventAutoFocus = () => {
// First, blur whatever element is active. This will make sure
// activeElement is the "default" active element
; (document.activeElement as any).blur()
const elem = document.activeElement as any
// ???: We need to set tabIndex, otherwise we won't get focus/blur events!
elem.tabIndex = 0
const focusElem = () => elem.focus()
elem.addEventListener("blur", focusElem)
elem.addEventListener("focusout", focusElem)
// On top of blur/focusout events, we need to periodically check the
// activeElement is the one we want because blur/focusout events aren't
// always triggered when document.activeElement changes
const interval = setInterval(() => { if (document.activeElement != elem) focusElem() }, 10)
// When the user starts interacting with the page, stop resetting focus
function stopResettingFocus() {
elem.removeEventListener("blur", focusElem)
elem.removeEventListener("focusout", focusElem)
clearInterval(interval)
window.removeEventListener("keydown", stopResettingFocus)
window.removeEventListener("mousedown", stopResettingFocus)
}
window.addEventListener("keydown", stopResettingFocus)
window.addEventListener("mousedown", stopResettingFocus)
}
const tryPreventAutoFocus = () => {
document.removeEventListener("readystatechange", tryPreventAutoFocus)
try {
preventAutoFocus()
} catch (e) {
document.addEventListener("readystatechange", tryPreventAutoFocus)
}
}
tryPreventAutoFocus()
})
// Add various useful modules to the window for debugging
import * as commandline_content from "@src/content/commandline_content"
import * as convert from "@src/lib/convert"