85

While searching for an answer in google, it seems that I'm not the only one stuck with a problem that seems impossible to solve.

I've managed to create a WebView with a custom WebViewClient - this makes it possible for me to have a processdialog and show an error message if an URL couldn't be loaded.

But this creates a problem with JavaScript. The URL I'm loading has some JavaScript which changes some HTML elements CSS styles (showing or hiding element) or redirects to another location onclick - or maybe even want's to show an alert box. But by using the WebViewClient none of those are working.

This is how I load a page:

public void loadUrl(String url)
{
    final ProgressDialog dialog = ProgressDialog.show(myActivity.this, "",  getString(R.string.loading), true);
            final WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setVerticalScrollBarEnabled(false);
            myWebView.setHorizontalScrollBarEnabled(false);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);                                         


            myWebView.setWebViewClient(new WebViewClient() 
            {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) 
                {
                    Toast.makeText(myActivity.this, url, Toast.LENGTH_SHORT).show(); //Debugging purposes
                if (url.endsWith(".mp4")) 
                {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.parse(url), "video/mp4");
                        view.getContext().startActivity(intent);  
                }
                else
                {                           
                        view.loadUrl(url);
                    }

                    return true;
                }

                public void onPageFinished(WebView view, String url) 
                {
                    //Toast.makeText(myActivity.this, "Oh no!", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }

                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
                {
                    Toast.makeText(myActivity.this, description, Toast.LENGTH_SHORT).show();
                    String summary = "<html><body><strong>" + getString(R.string.lost_connection) + "</body></html>";
                    myWebView.loadData(summary, "text/html", "utf-8");   
                }              

             }); //End WebViewClient

            myWebView.loadUrl(url);     
        }

This could probably be done in a smarter way, but I'm new at both Java and Android development...

Is it possible for me to enable the JavaScript for the WebViewClient at all? Removing the WebViewClient solves the problem, but then I can't catch events when the page errors or is finished loading.

Repox
  • 15,015
  • 8
  • 54
  • 79

9 Answers9

162

I don't know what your exact problem is, but i can enable the JavaScript and a custom WebViewclient without any problem:

WebView vistaWeb = (WebView) findViewById(R.id.webview);
vistaWeb.setWebChromeClient(new MyCustomChromeClient(this));
vistaWeb.setWebViewClient(new MyCustomWebViewClient(this));
vistaWeb.clearCache(true);
vistaWeb.clearHistory();
vistaWeb.getSettings().setJavaScriptEnabled(true);
vistaWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mdelolmo
  • 6,417
  • 3
  • 40
  • 58
  • 13
    It seems that WebChromeClient is the solution. By adding myWebView.setWebChromeClient(new WebChromeClient()); to my code it solved the JavaScript problem. I hope my question helps other Googlers in the future then. Thank you. – Repox Feb 23 '11 at 11:07
  • 5
    Yes, this is one of the mysterious hack. for Monodroid C#, adding `wv.SetWebChromeClient(new WebChromeClient());` worked.. –  Dec 31 '13 at 00:51
  • @Repox Maybe you should add that as an answer as it is simple and seems to work. – ban-geoengineering Jun 25 '15 at 14:43
  • agree, WebChromeClient is the solution – danisupr4 Mar 27 '17 at 11:24
  • @mdelolmo hi, could you please help me out at here https://stackoverflow.com/questions/63498385/how-to-pass-parameters-in-webview? – pratik vekariya Aug 20 '20 at 07:04
  • You can Use `MyCustomChromeClient` instand of `WebChromeClient` and `MyCustomWebViewClient` instand of `WebViewClient` , its work foe me. – Urvish Vocsy Sep 29 '22 at 04:52
11

The proper way to enable JavaScript is by add the below two lines:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

Even if after adding its not working then try adding the below line.

mWebView.getSettings().setDomStorageEnabled(true);

Now It should work. :)

Tatson Baptista
  • 445
  • 3
  • 6
  • 18
7

Try this to enable javascript

WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(url);
Marian Nasry
  • 821
  • 9
  • 22
Rishabh Gupta
  • 119
  • 1
  • 5
3

What happened in my case : I was serving local html files and when applying

    web.getSettings().setJavaScriptEnabled(true);
    web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

but then my urls stopped working. Solution to make both JS and local href work was to add

    web.getSettings().setAllowFileAccess(true);
    web.getSettings().setAllowFileAccessFromFileURLs(true);

where

    web = (WebView) findViewById(R.id.embedded_web);
3

This code happen to works for me, I hope it can helps you and other developer:

webview = findViewById(R.id.WebView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.loadUrl("www.example.com");
WetzelSchultz
  • 67
  • 1
  • 10
2

-> Hello Please Try This Code This Code Run Fine

-> For More Information of Documentation Please Visit https://developer.android.com/guide/webapps/webview#java

-> This Link Work Fine in Nov 2019 Currently I Don't Know

-> Your XML Code For Design is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


</LinearLayout>

-> And Your Java Code For Backend is

package com.developer.harshil.kaneria.webview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView myWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.loadUrl("https://github.com/Harshil-Kaneria");
    }
}

-> Here in Java Code

WebSettings webSettings = myWebView.getSettings();

And This

webSettings.setJavaScriptEnabled(true);

-> It is Allow To JavaScript Run When Page is Load

-> Thanks A Lot For Read.

Harshil Kaneria
  • 153
  • 1
  • 2
  • 9
1

Do "Javascript-URLs" get routed through shouldOverrideUrlLoading? Try checking that and if so, return false for links like that (so that the webview handles the link, not your WebViewClient)

Timo Ohr
  • 7,947
  • 2
  • 30
  • 20
0

Similar to @mdelolmo answer, but in Kotlin:

    webview.setWebChromeClient(WebChromeClient())
    webview.setWebViewClient(WebViewClient())
    webview.clearCache(true)
    webview.clearHistory()
    webview.getSettings().setJavaScriptEnabled(true)
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true)
Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
  • Your answer will not help anyone as is the same as Java and there's nothing special about Kotlin. – alizeyn Aug 18 '19 at 13:30
  • 1
    @Ali Zeynali If there is someone start off with Kotlin as their first programming language and not familiar with Java, then this answer is useful – Jerry Chong Aug 30 '19 at 05:25
0

How enable programmatically answered in other answers. But some javascripts not worked if your webview is in nestedscrollview. Remove it and add webSettings.setJavaScriptEnabled(true);

dimvolk
  • 338
  • 3
  • 9