Sujit
Sujit

Reputation: 658

window.getselection is not working in android

I am new to use html+javascript+jQuery. I am trying to use window.getSelection to get selected text but this is not working. Can any one suggest solution for this.

Thanks in advance.

Upvotes: 2

Views: 2243

Answers (4)

portal TheAnGeLs
portal TheAnGeLs

Reputation: 389

I know this is a very old question, but I get this as a first search result when I had tried to resolve the same or similar issue. I didn't find a solution here but after some time I realized that sometimes for phones there should be a short timeout between click and selection to make getSelection() work properly.

So e.g. instead this:

document.getElementById("element").addEventListener('click', function (event) {
    window.getSelection().selectAllChildren(this)
});

You should use somethink like this:

document.getElementById("element").addEventListener('click', function (event) {
  setTimeout(function(passedThis) {
    window.getSelection().selectAllChildren(passedThis)
  }, 10, this);
});

Maybe it save some time to somebody.

Upvotes: 1

DevAb
DevAb

Reputation: 598

If you want to call a function right after a text selection, you can use the "selectionchange" event:

document.addEventListener("selectionchange", handleSelection);

It's working for android chrome and iOS safari.

Upvotes: 0

Abhishek
Abhishek

Reputation: 3398

Just need simple line of code in java script which done your job

 //I am using below line of code which works in both android and web browsers.

function getSelectedText() {
    var selection = null;

    if (window.getSelection) {
        selection = window.getSelection();
    } else if (typeof document.selection != "undefined") {
        selection = document.selection;
    }

    var selectedRange = selection.getRangeAt(0);

    console.log(selectedRange.toString());
}

NOTE : Don't call this method in post or inside any runnable interface as post or any runnable interface make delay in calling this method(Method call happens after browser selection release). Just call this method like

webView.loadUrl("javascript:getSelectedText()");

Upvotes: 2

Marcus Soares
Marcus Soares

Reputation: 1

Try

function getSelected() {
var text = "";
if (window.getSelection && window.getSelection().toString() && $(window.getSelection()).attr('type') != "Caret") {
    text = window.getSelection();
    return text;
} else if (document.getSelection && document.getSelection().toString() && $(document.getSelection()).attr('type') != "Caret") {
    text = document.getSelection();
    return text;
} else {
    var selection = document.selection && document.selection.createRange();
    if (!(typeof selection === "undefined") && selection.text && selection.text.toString()) {
        text = selection.text;
        return text;
    }
}
return false;
}

Upvotes: -1

Related Questions