Skip to main content

Attaching an event listener to all possible text fields

I am developing a chrome extension. How can I efficiently attach an event listener to all text fields, including input type text, textarea, content editable, even for dynamically added fields and fields within iframes? Is it possible to limit the attachment only to visible or active elements instead of searching all fields at once?

Currently, I am using the following code, but I'm looking for a more optimised solution:

function getNodes(selectors, callback) {
    const nodeList = document.querySelectorAll(selectors);
    const nodes = Array.from(nodeList);
    nodes.forEach(node => callback && callback(node));
    const mutationObserver = new MutationObserver(() => {
        const newNodes = Array.from(document.querySelectorAll(selectors));
        const addedNodes = newNodes.filter(node => !nodes.includes(node));
        addedNodes.forEach(node => nodes.push(node) && callback && callback(node));
    });
    mutationObserver.observe(document.body, { childList: true, subtree: true });
    return nodes;
}

const onActivateScript = () => {
    getNodes(selectors,node => {
        node.addEventListener('keydown', ()=>{});
    });
}

window.addEventListener('activateScripts', onActivateScript);

I also discovered today there are shadowroot elements on few pages. I am thinking to use following code.

function getActiveElement(element = document.activeElement) {
    const shadowRoot = element.shadowRoot
    const contentDocument = element.contentDocument

    if (shadowRoot && shadowRoot.activeElement) {
        return getActiveElement(shadowRoot.activeElement)
    }

    if (contentDocument && contentDocument.activeElement) {
        return getActiveElement(contentDocument.activeElement)
    }

    return element
}

But is there a more streamlined approach to attaching event listeners to all text fields, possibly focusing on visible or active elements instead of searching complete DOM at once.

Via Active questions tagged javascript - Stack Overflow https://ift.tt/kpJ5szU

Comments