Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
Chrome extension: cannot use `document.querySelector().click()` after using `document.getSelection()`

My extension allows you to either enter or copy some text from the page (using document.getSelection()) and then tries to click a button by using document.querySelector and then the click event.

If I enter the text manually, everything works as expected. However, if I paste the text into the extension using getSelection, the click event gets lost.

For reference, this is an abbreviated version of my code:

//content.js
function messagesFromReactAppListener(msg, sender, sendResponse) {
    switch (msg.method) {
        case "getSelection":
            sendResponse({ text: document.getSelection().toString() });
            break;
        case "replyToEmail":
            const replyBtn = document.querySelector(...);
            if (replyBtn) {
                replyBtn.click();
                sendResponse(true);
            } else {
                sendResponse(false);
            }
            break;
    return true;
}
// paste function, called when button pressed on extension
export function pasteText(): Promise<PasteTextRespType> {
    return new Promise((resolve) => {
        chrome.tabs &&
            chrome.tabs.query(
                {
                    active: true,
                    currentWindow: true,
                },
                (tabs) => {
                    chrome.tabs.sendMessage(tabs[0].id || 0, { method: "getSelection" }, (response: PasteTextRespType) => {
                        resolve(response);
                    });
                }
            );
    });
}
// associated with a submit button on the extension
handleSubmit(event: any) {
        ...

        chrome.tabs && chrome.tabs.query({
            active: true,
            currentWindow: true
        }, tabs => {
            chrome.tabs.sendMessage(
                tabs[0].id || 0,
                { method: REACT_MSG_METHODS.replyToEmail },
                (resp) => {
                    ...
                }
            );
        });
        event.preventDefault();
    }

I do know it would be best if I had a listener on the click event before sending response with true, but I haven't been able to do it the right way. Help with that would also be appreciated, but click just doesn't work after using paste above.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It only took me 5 days to figure this out, and it was driving me absolutely crazy. Turns out, when you do document.getSelection() that sets the focus on whatever you select, which prevents click events from being fired on other elements. It was weird because I could, for example, change the background css of the selected element. The solution was to change the getSelection case to:

        case "getSelection": {
            let sel = document.getSelection();
            sendResponse({ text: sel.toString() });
            sel.removeAllRanges();
            break;
        }

Which removes focus / the selection and enables the click to fire.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda