window.getSelection() actually works fine. The problem here is because when the focus is lost, then the selection is cleared as well.