Search code examples
javascriptgoogle-chrome-extensionevent-handlingkeydowntext-manipulation

Trouble with 'keydown' Event in Chrome Extension: Capturing Backspace Action


I am creating a Chrome extension (code here) and am having trouble with the "keydown" event. I want to use it to capture a 'backspace' before it happens, in order to switch the text the user is typing before it is deleted. However, with the current way I am doing things, which involves creating a function keyDown(event){...} and adding document.addEventListener("keydown", keyDown), when the function is called, the event.srcElement.innerText contains the text after the deletion takes place. To clarify, if an editable element contains 'abcd' and I press backspace, I will get the text 'abc' from the event handler, rather than 'abcd'.

P.S. If you view my code and notice any other issues with it, please do let me know. I am not a seasoned developer and would appreciate any input.


Solution

  • Thank you @wOxxOm for the answer. I just needed to change document.addEventListener('keydown', function) to window.addEventListener('keydown', function, true) and the function launched before the text was deleted by a backspace.