Use the rangy TextRange module for serializing selections. Notably slower, but more accurate although not perfect.