Yizzy Wu Yizzy Wu - 4 years ago 126
Javascript Question

Chrome extension: How to inject button to an onfocus div(texterea/input) in the page? especially in facebook page

I have been trying to find a way to inject a button when a textarea in the window document got clicked(onfocus) ...for weeks, but I failed to do so.

The function is similar as how Grammarly's extension does.
Grammarly's extension

The thing is, I want to add a button nearby or in the textarea when it is onfocus or keypressed. Then I could return the text value to the extension. What is the right way to detect the div in the content script?

the button code is like this:

function appendBtn (){
var btn = document.createElement("INPUT");
btn.setAttribute("type", "button");
btn.setAttribute("value", "button");
document.body.appendChild(btn);
}

document.onclick = function() {
appendBtn();
}


what I want is to find the right div instead of appending the element after body...which it always show at the bottom of the page, especially on facebook page, which I can't even target the input boxes of the comment area..

Please help me with this! I am so desperate right now...

Answer Source

Use the focusin event (it bubbles unlike the focus event) in a content script of your extension:

var btn = createButton();
document.addEventListener('focusin', onFocusIn);

function onFocusIn(event) {
    var el = event.target;
    if (el.contentEditable ||
        el.matches('input, textarea') && el.type.match(/email|number|search|text|url/))
    {
        appendButton(el);
    }
}

function createButton() {
    var btn = document.createElement('button');
    btn.textContent = 'Yay!';
    btn.onclick = function(event) {
        btn.textContent += '!';
    };
    return btn;
}

function appendButton(textElement) {
    textElement.parentElement.insertBefore(btn, textElement.nextElementSibling);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download