|
53 | 53 | range.detach(); |
54 | 54 |
|
55 | 55 | // modify() works on the focus of the selection |
56 | | - const endNode = sel.focusNode; |
57 | | - const endOffset = sel.focusOffset; |
| 56 | + let endNode = sel.focusNode; |
| 57 | + let endOffset = sel.focusOffset; |
58 | 58 | sel.collapse(sel.anchorNode, sel.anchorOffset); |
59 | 59 | sel.modify('move', direction[0], 'character'); |
60 | 60 | sel.modify('move', direction[1], 'word'); |
61 | | - // remove the whitespace after the word |
62 | | - if (direction[0] === 'backward') { |
63 | | - sel.modify('move', 'backward', 'character'); |
64 | | - } |
65 | 61 | sel.extend(endNode, endOffset); |
66 | 62 | sel.modify('extend', direction[1], 'character'); |
67 | 63 | sel.modify('extend', direction[0], 'word'); |
68 | | - // remove the whitespace after the word |
69 | | - if (direction[0] === 'forward') { |
| 64 | + |
| 65 | + // It seems in Chrome when moving a word, it would count the following whitespace of the word. |
| 66 | + // A problem with the whitespace is if users repeat the action, the selection would be extended unexpectedly. |
| 67 | + // The following code removes that whitespace. |
| 68 | + if (direction[0] === 'forward' && |
| 69 | + sel.focusNode.textContent.charAt(sel.focusOffset - 1) === ' ') { |
| 70 | + // for the forward selection, the whitespace could appear in the focusNode |
70 | 71 | sel.modify('extend', 'backward', 'character'); |
| 72 | + } else if (direction[0] === 'backward' && |
| 73 | + sel.anchorNode.textContent.charAt(sel.anchorOffset - 1) === ' ') { |
| 74 | + // for the backward selection, the whitespace could appear in the anchorNode |
| 75 | + endNode = sel.focusNode; |
| 76 | + endOffset = sel.focusOffset; |
| 77 | + sel.collapse(sel.anchorNode, sel.anchorOffset - 1); |
| 78 | + sel.extend(endNode, endOffset); |
71 | 79 | } |
72 | 80 | } |
73 | | - return sel.toString().trim(); |
| 81 | + return sel.toString(); |
74 | 82 | }; |
75 | 83 |
|
76 | 84 | browser.runtime.onMessage.addListener((request, _, sendResponse) => { |
|
0 commit comments