Skip to content
Snippets Groups Projects
autofocus.js 784 B
document.addEventListener('DOMContentLoaded', function() {
	if ('MutationObserver' in window) {
		const config = {
			attributes: false,
			childList: true,
			subtree: false,
		}

		function onElementAdded(mutationsList, observer) {
			for (const mutation of mutationsList) {
				if (mutation.type === 'childList') {
					if (mutation.addedNodes.length > 0) {
						for (const node of mutation.addedNodes) {
							if (node.nodeName.toLowerCase() === 'canvas') {
								node.focus();
								if (window.focusHandler) {
									window.focusHandler.disconnect()
									delete window.focusHandler
								}
								return
							}
						}
					}
				}
			}
		}

		window.focusHandler = new MutationObserver(onElementAdded)
		window.focusHandler.observe(document.body, config)
	}
})