I think this line will throw an error if there's no selection, maybe first perform a check using selection.rangeCount?