king cannibal
king cannibal

Reputation: 15

evaluate Javascript doesn't run in web view

I'm trying to interact with my web view so I can get a value to later insert into a file (which is not important), When trying to execute the JavaScript I tried adding script tags and also removing the function which both ways don't work. I don't get any error in any way at all. How do I execute JavaScript in a loaded web view?

 WebView myWebView = (WebView) findViewById(R.id.webload);


        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("https://www.example.co.uk");
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.setWebViewClient(new WebViewClient() {
                                       @Override
                                       public void onPageFinished(WebView view, String url) {
                                           view.evaluateJavascript("(function(){alert('e');})();", givenValue -> {

                                               if (givenValue != null && !givenValue.isEmpty() && !givenValue.equals("null")) {
                                                  
                                               }
                                           });
                                           super.onPageFinished(view, url);
                                       }
                                   }
        );

Upvotes: 0

Views: 291

Answers (1)

Sampat Sharma
Sampat Sharma

Reputation: 89

Hey i have worked used webview alot in my recent projects and the right way to execute the javascript in a loaded webpage is below.

webview.loadUrl("javascript:(function() {
         // Your Javascript code , you can access dom elements and do whatever you want
      })()");

Add this line in onPageFinished function of WebViewClient. also don't forget to enable javascript of your webview

Upvotes: 0

Related Questions