Created
November 3, 2023 14:49
-
-
Save plateaukao/e8b4cbf7ac6ba9060a402591b17a6081 to your computer and use it in GitHub Desktop.
addTextSelectionChangeListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var selectedText = ""; | |
function getSelectionPositionInWebView() { | |
let selection = window.getSelection(); | |
if (selection) { | |
let range = selection.getRangeAt(0); | |
let startNode = range.startContainer; | |
let startOffset = range.startOffset; | |
let endNode = range.endContainer; | |
let endOffset = range.endOffset; | |
let start = getRectInWebView(startNode, startOffset); | |
let end = getRectInWebView(endNode, endOffset); | |
// Send anchor position to Android | |
if (selection.toString() != selectedText) { | |
selectedText = selection.toString(); | |
if (selectedText.length > 0) { | |
androidApp.getAnchorPosition( | |
start.left, | |
start.top, | |
end.right, | |
end.bottom, | |
); | |
} | |
} | |
} | |
} | |
function getRectInWebView(node, offset) { | |
let range = document.createRange(); | |
range.setStart(node, offset); | |
range.setEnd(node, offset); | |
let rect = range.getBoundingClientRect(); | |
return rect; | |
} | |
// Call the function to get selection position | |
document.addEventListener("selectionchange", function () { | |
getSelectionPositionInWebView(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment