Issue with Android: The function window.getSelection() is not functioning properly within webview

Having an app with a webview, I have been struggling to retrieve user-selected text from the body of the webview. While iOS handles this task seamlessly, Android falls short in this aspect, posing a challenge for me. Despite scouring various resources, including websites and Google, I couldn't find a solution. Fortunately, my app features a javascript interface that allows communication with a script loaded into the webview. My initial idea was to utilize javascript to extract the text from the webview. In Chrome, I managed to achieve this using the following javascript snippet:

window.getSelection.toString();

Currently, I have a button triggering a function in my js file, executing the above command and passing the results to a method in my javascript interface. The information is then displayed through a toast message. However, after selecting text and clicking the button, the toast message only shows:

javascript returned:  

instead of:

javascript returned: <my selected text>

Upon removing the '.toString();' part from the javascript command and attempting to select text again before pressing the button, the message displayed reads:

javascript returned: undefined

This issue leaves me puzzled. Here's the relevant code snippet showing the javascript function being called:

myNameSpace.getTextSelection = function()
        {
            var str;
            if (window.getSelection){
                str = window.getSelection().toString();
            } else {
                str = 'does not';
            }
            window.myJSHandler.getSelectedText(str);
        };

Additionally, here's the Java function being invoked:

public void getSelectedText(String text)
        {
            String str = "function called.  it returned: " + text;
            Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
        }

Answer №1

Found the perfect solution that works for me!

//This snippet of code that I am using has proven to work seamlessly on 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());
}

Please take note: Avoid calling this method within a post or any runnable interface as it may cause delays in execution due to browser selection release. Instead, simply invoke this method like so:

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

Answer №2

In Android, text selection occurs in a separate class called WebTextView. If we attempt to retrieve the selected word using a JavaScript method:

var range = window.getSelection ();  

This function may not return anything. If you need the selected word, reflection can be used for that purpose. If necessary, I can provide the code for that later.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to pass an input value into a function when a form is submitted in Angular 6?

When I press enter, my code works perfectly and the performSearch function runs successfully. However, when I attempt to run the function by clicking the submit button, I encounter the following error: Error: cannot read property of undefined This is m ...

What is the best way to position the navbar above all the other text content?

I'm experiencing an issue where the navbar is not appearing on top of all the text/buttons. How can I adjust it so that the navbar appears on top? Thank you. https://i.sstatic.net/59M2l.png [Codepen](https://codepen.io/turbo0/pen/NWBMNQr) ...

NightwatchJS "comes to a standstill"

We have encountered an issue with our Nightwatch tests not running after transitioning from Windows to Linux. The tests simply freeze. Although the Selenium server is actively listening and the chrome_driver (linux 64 bit) setting has been configured corr ...

How can Vue.js use the v-if directive for events?

Is it possible to react to an event within a vue template? For example, if a child component dispatches an event like $dispatch('userAdded'), can I display a message in the parent component based on that? <div class="alert alert-info" v-if="u ...

Is it possible to add to JSON formatting?

Here is the JSON object I have: new Ajax.Request(url, { method: 'post', contentType: "application/x-www-form-urlencoded", parameters: { "javax.faces.ViewState": encodedViewState, "client-id": options._clientId, ...

The JSON data URLs in the `_next/data` directory of the NextJS app are returning a 404 error, however, when accessed directly in the

I am facing an issue with my Next.js (v13) app hosted on a self-hosted Kubernetes cluster. The AJAX JSON data calls from the _data directory are showing as 404 errors, even though when I directly visit the URLs in my browser, they load fine. I'm perp ...

What is the best way to showcase an image using Next.js?

I'm having a problem with displaying an image in my main component. The alt attribute is showing up, but the actual image is not appearing on the browser. Can someone please point out what I might be doing wrong? import port from "../public/port. ...

The timer countdown is encountering an issue where it cannot update the 'textContent' property of a null element

I'm encountering errors with a countdown script that I can't seem to resolve. The error message is generating 1 error every second: Uncaught TypeError: Cannot set property 'textContent' of null at (index):181 (anonymous) @ (index):181 ...

Reactjs is currently not integrated with Firebase

I recently completed a project in reactjs and realized it requires authentication. My initial thought was to connect it with Firebase as it seemed like the most straightforward option. Following a tutorial on YouTube, however, I encountered some difficult ...

ERROR: Angular 2 custom form input provider not found

I am currently working on incorporating ControlValueAccessor into a custom Angular 2 form input component. However, I encountered an EXCEPTION: EXCEPTION: No provider for MyDatePicker! (MyDatePickerValueAccessor -> MyDatePicker) I have shared t ...

Utilizing AngularJS to display a list of data on a Flot bar chart by triggering a click event

I am relatively new to utilizing angularjs and flot bar chart functionalities. Currently, I am attempting to exhibit filtered data in a curated list upon clicking, based on specified filters. To accomplish this, I have developed a personalized directive ...

The issue of losing focus while using a Bootstrap 4 modal over another modal

Issue with Bootstrap 4: When opening the first modal, the focus becomes trapped inside it, preventing users from focusing on elements outside of the modal. The same issue occurs when opening the second modal – the focus remains trapped within it as inten ...

Attempting to bypass the NetworkOnMainThreadException error when using AsyncTask in order to display a ProgressDialog

Having an issue with the DropBox SDK while trying to upload a file to Dropbox. Everything works smoothly until the cancel button is pressed in the ProgressDialog during the file upload process inside an AsyncTask. This action triggers a NetworkOnMainThread ...

Will a JavaScript source map file continue to function properly even after the source code file has been minified?

My experience I specialize in utilizing TypeScript and Visual Studio to transform highly organized code into functional JavaScript. My skills involve configuring the project and Visual Studio to perform various tasks: Merging multiple compiled JavaScrip ...

Searching for checkboxes within a list on a webpage using jQuery - what's the trick?

I'm dealing with a large list of checkbox options, potentially over 500 checkboxes. To make it easier for users, I want to implement a simple search box that allows them to quickly find and select the checkbox they're looking for. I plan on using ...

Having trouble initiating a new activity with Android intent?

Trying to accomplish a simple task, I want to start a new activity from my main one. Here's the code snippet: public class mainActivity extends Activity { /** onCreate method to initialize the activity */ @Override public void onCreate(Bundle saved ...

Issue with react-addons-css-transition-group and multiline TextFields in Material-UI TextField

If a TextField with multiline is nested inside a react-addons-css-transition-group, it seems to disrupt the show transition. Any suggestions on how to handle this situation effectively? Check out my code snippet here: https://codesandbox.io/s/material-dem ...

Alter the background color of the entire document to (EDIT) in the top dialog box

<script> $(function() { $( "#dialog" ).dialog(); }); </script> </head> <body> <div id="dialog" title="Basic dialog"> <p>This default dialog box can display information. It can be moved, re-sized, and closed ...

What is the best way to direct to a specific URL upon successful login?

My goal is to create a dynamic redirect feature for users after they log in. For instance, if a user types a URL like http://localhost:3000/login/tickets, the program should direct them to the login page if they are not already logged in. After logging in, ...

Communication between Nodemailer and Mailgun

I keep encountering an authentication issue while trying to use Nodemailer with Mailgun. I followed the Nodemailer documentation which states compatibility with Mailgun SMTP, but unfortunately, I am consistently facing this error when executing my applicat ...