Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Tracking Selection Change on Firefox for Android

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!):

  1. Tried catching the "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!
  2. Tried doing the same with the "touchend" event - Same result.
  3. Tried catching the "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.

like image 217
techfoobar Avatar asked Aug 20 '16 04:08

techfoobar


1 Answers

1) Native Text Selection Events

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.

 

2) Find events that work

(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);
}

 

3) Hacking

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().

like image 77
Gerald Avatar answered Nov 15 '22 17:11

Gerald