Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this title to display my own text. How can I achieve this?

Answer №1

After spending some time on it, I managed to tackle this issue by incorporating the setWebChromeClient method:

webView.setWebChromeClient(new WebChromeClient() {

    @Override
    public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
        AlertDialog dialog = new AlertDialog.Builder(view.getContext()).
                setTitle("YourAlertTitle").
                setMessage(message).
                setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //do nothing
                    }
                }).create();
        dialog.show();

        return true;
    } }); 

Answer №2

MKY's answer is effective if your focus is solely on triggering the alert function. However, if you also need to address the functionalities of confirm and prompt, additional steps must be taken to override the onJsConfirm and onJsPrompt methods.

An important distinction between alert and confirm is that for confirm, it is necessary to incorporate a setNegativeButton that invokes the result.cancel() method within the lambda expression.

Dealing with prompt is more complex as it involves integrating a text editor into the dialog box. To achieve this, an EditText object needs to be created and included in the dialog using AlertDialog.Builder.setView, detailed in this specific response.

Furthermore, implementing a dismiss listener using setOnDismissListener across all three dialogs is advisable to account for scenarios where the dialog may be dismissed through means other than button clicks. This could occur if the user presses the back button or selects an area outside the dialog.

The following comprehensive code accommodates alert, confirm, and prompt situations. Remember to customize the placeholder "Title" in each respective method according to your desired title preference.

webView.setWebChromeClient(new WebChromeClient(){
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result){
        new AlertDialog.Builder(view.getContext())
            .setTitle("Title")
            .setMessage(message)
            .setPositiveButton("OK", (DialogInterface dialog, int which) -> result.confirm())
            .setOnDismissListener((DialogInterface dialog) -> result.confirm())
            .create()
            .show();
        return true;
    }

    @Override
    public boolean onJsConfirm(WebView view, String url, String message, JsResult result){
        new AlertDialog.Builder(view.getContext())
            .setTitle("Title")
            .setMessage(message)
            .setPositiveButton("OK", (DialogInterface dialog, int which) -> result.confirm())
            .setNegativeButton("Cancel", (DialogInterface dialog, int which) -> result.cancel())
            .setOnDismissListener((DialogInterface dialog) -> result.cancel())
            .create()
            .show();
        return true;
    }

    @Override
    public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result){
        final EditText input = new EditText(view.getContext());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        input.setText(defaultValue);
        new AlertDialog.Builder(view.getContext())
            .setTitle("Title")
            .setMessage(message)
            .setView(input)
            .setPositiveButton("OK", (DialogInterface dialog, int which) -> result.confirm(input.getText().toString()))
            .setNegativeButton("Cancel", (DialogInterface dialog, int which) -> result.cancel())
            .setOnDismissListener((DialogInterface dialog) -> result.cancel())
            .create()
            .show();
        return true;
    }
});

Answer №3

Here is an example written in Kotlin:

It is crucial not to forget adding result.confirm(), as it will prevent your Webview from freezing!

override fun onJsAlert(
        view: WebView,
        url: String,
        message: String,
        result: JsResult
    ): Boolean {
        val title = "yourtitle"
        val dialog: AlertDialog =
            AlertDialog.Builder(view.context).setTitle(title).setMessage(message)
                .setPositiveButton("OK",
                    { dialog, which ->
                        result.confirm()
                    }).create()
        dialog.show()
        return true
}

On a side note, for individuals seeking a solution using both WebViewClient() and WebChromeClient(), it is possible to utilize them simultaneously. Not all override methods are available in one type of browser. Here is a way to implement this. Include

WebView.webChromeClient = ChromeClient()
and:

inner class ChromeClient internal constructor() : WebChromeClient() {
//Implement your methods here
}

Then proceed with launching the regular WebViewClient to perform tasks

WebView.webViewClient = object : WebViewClient() {
//Code implementation goes here
}

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

Concerns arise when dealing with a jar file that contains external libraries

I am facing an issue with starting my program from a jar file that I created. It runs perfectly fine when launched from IntelliJ, but when I try to start it from the jar file, it fails to work. I used IntelliJ to create the jar and my project was built usi ...

Revamping status and backend systems

Seeking advice on the most effective method to execute a HTTP PUT request within my react application. A Post component is responsible for fetching data from https://jsonplaceholder.typicode.com/posts/1 and displaying it. There's another component na ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

Efficiently sift through a vast assortment using a filtering method

Currently, I am developing an application similar to Uber which involves managing a collection of drivers with their current positions (latitude and longitude). One specific requirement is to find drivers who are within a 200-meter distance from the user& ...

What is the alternative to using document.getElementById?

1) Question 1 Why does the following example work without using "document.getElementById('myId')" and is it acceptable to skip this step? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Javascript quest ...

Guide on applying a filter to the items in a listbox using the input from a text box

In my HTML form, I have the following elements: 1) A list box containing filenames: s1.txt2013 s2.txt2013 s3.txt2012 s4.txt2012 2) A text box where the user enters a pattern (e.g. 2013) 3) A button By default, the list box contains the 4 file ...

What could be causing the issue with the exports field in package.json not functioning properly within

Recently, I created an npm package that includes three js files. Now, in my current project, I am aiming to import these js files using the following syntax: import MyButton from '@bslm/ui/MyButton' To achieve this, I made sure to specify the ex ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

This JavaScript function assigns a value to an input field in a form, only to have the value vanish soon after

I'm attempting to create a dynamic database search using ajax with a form input field. Currently, I am able to choose a text from the suggested list and trigger the "livesearchSelect" event, which sets the value of the input field. However, the set va ...

Utilizing a nested ajax call to pass a value from the first call to the URL of the second ajax call

I am working on implementing live search functionality, where I need to pass an id value obtained from the first ajax call to the second one. Currently, when I type rapidly into the search field, I am able to retrieve the information. However, if I perfor ...

Verify if a list of lists includes any sublists that contain an element from another list

I found a helpful solution here that I implemented to verify if a List<List<String>> contains a sublist matching any element from another List. for (List<String> text1List : text2ListOfLists) { System.out.println("text1List = " + te ...

Switching back and forth between two different numbers with the help of React.useState hooks

Can someone help me with the logic using React.useState hooks? I'm trying to toggle the "volume" option in the state of the "PlayOn" object between 0 and 0.75. I am not very experienced with React. I need help with the function logic for soundChange ...

Developing a synchronous loop in Node.js using the web-kit module

My goal with my app using node.js and webkit is to scan each proxy listed in a file.txt and determine if the proxy is working. However, I am encountering an issue where my loop does not wait for the "http.get" test on line 11 to complete before moving on ...

using ng-show to display array elements

There is a syntax error showing up on the console for the code below, but it still functions as intended. Can someone help identify what I might be missing? <p class="light" data-ng-show="selectedAppType in ['A1','A2','A3' ...

Is there a way to make a text area box visible using JavaScript?

Currently, I am developing an automation script in Python using Selenium. My objective is to make a textarea box visible, as I need to insert some arguments into it. Here is the code snippet that I am utilizing: element = driver.find_element_by_id('g ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...

Press on the button that is currently in your field of view

I have a web page with multiple buttons inside div elements. I am looking to automate the process of clicking the "Buy" button that is currently visible on the screen when the user presses the B key. $(document).keydown(function(e) { if (e.keyCode == ...

TinyMCE toolbar missing the "hr" option

I am encountering an issue while using TinyMCE as my editor. I have added the plugin as instructed, but I cannot find the "hr" button/option in the editor interface. If anyone has any insights or solutions to this problem, please share! This is how I am ...

Looking to display an element right away, like a loading spinner, in Vue? If nextTick isn't doing the trick, here's what you can try

Imagine having a Vue component stored in a .vue file with a data member called isLoading: false. The template includes: <div v-show="isLoading" id="hey" ref="hey">Loading...</div> <button @click="loadIt()">Load it</button> Along w ...