Selecting some text on a page and then clicking a button preserves text selection in pretty much any browser other than Safari (at least its mobile version).
Is there any way to make Safari behave just like everything else?
Simple jsFiddle demonstrating the problem, where selecting some text and clicking the button doesn't report selected text in Safari (selection is removed and window.getSelection() returns nothing): https://jsfiddle.net/u5b3awhd/
<span>here's some text to select</span>
<button onclick="showSelection()">click me</button>
<div id="message"></div>
function showSelection() {
document.getElementById("message").innerText = "selected " + window.getSelection();
}
I've tried adding user-select: none and similar styles to the button, but it didn't help.
I also found some recommendations to get selected text on some other input events (mouse events etc.), but there are 2 major reasons I'm looking for a better solution:
- It looks a little hacky, especially since this needs to run on mobile, where there is no mouse, so those events are emulated and might be tricky to get right without other undesirable side effects. Although the
selectionchangeevent might partially solve this problem, there is still another problem #2... - Text selection in browser UI actually gets lost and the user needs to select it again later, which is not the best experience, especially considering that it works great in other browsers.
So how does everyone solve this in 2022?