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.
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.