I'm looking for a way to track the text selection on a web page. I need some code to be executed whenever there is a change in selection. I have successfully done this on all major desktop browsers, but the same does not seem to be working on Firefox for Android.
I tried three approaches (none of them worked!):
"mouseup"
event and checking if there is a
non-empty text selection. Problem is "mouseup"
isn't getting
triggered if a selection was made during the mousedown-move-up
sequence! "touchend"
event - Same result."selectionchange"
event. I saw that it isn’t
triggered when the selection changes as it needs the config key
"dom.select_events.enabled"
to be set. This is false
by default and I obviously can't ask my visitors to tweak browser settings :-)Also, as expected, the first two events don't get triggered if the selection is extended or reduced by dragging the selection start/end markers.
The only solution I can think of now is a periodic poller (using setInterval) that checks if there is a text selection. This is definitely unclean and anti-performance.
Any alternatives and/or advice will be very helpful.
Currently, polling seems to be the only work-around.
However, the selectionchange
event is currently experimentally implemented in Firefox for Android Nightly. It can be enabled by setting the dom.select_events.enabled
flag to true
(defaults to false
).
In Nightly builds, this flag already defaults to true
, so there is a chance you can use it normally in a couple of months.
(UNTESTED!!)
Even if onselectstart
cannot be used productively in Firefox for Android yet, the only viable easy solution is polling.
To improve performance and reduce costs, polling can be started on the window blur
event. Because whenever the user is making a selection, the focus should be set off the viewport (untested though).
window.addEventListener('blur', function(){
// start polling for text selections
});
When the focus is given back, polling can be stopped.
window.addEventListener('focus', function(){
// stop polling
});
To check if the browser actually supports text selection events, you can use this function:
var browserSupportsTextSelectionEvents = function(){
return !!('onselectstart' in document.body);
}
A third idea is to disable text selection for mobile Firefox users via CSS (-moz-user-select: none
), implement a custom text selection function based on touch start and end positions and pushing the native selection range back to the browser via HTMLElement.setSelectionRange()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With