Calling javascript function from android webview?

2020-03-31 06:32发布

I try to call a javascript function from directly form my application (webview.apk), in order to start a script which would autoplay a html5 video clip, I have tried to add itt right after webview loadURL but wwithout luck.

Maybe someone could take a look at the code. What am I missing? Thanks!

package tscolari.mobile_sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;

import android.media.MediaPlayer;


public class InfoSpotActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.main);

        WebView mainWebView = (WebView) findViewById(R.id.mainWebView);

        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mainWebView.setWebChromeClient(new WebChromeClient());

        mainWebView.setWebViewClient(new MyCustomWebViewClient());
        mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);




        mainWebView.loadUrl("http://server.info-spot.net");
        mainWebView.loadUrl("javascript:playVideo()");


    }


    private class MyCustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

2条回答
Rolldiameter
2楼-- · 2020-03-31 06:32

Kotlin Code to call jsFunction:

webView.webViewClient = object : WebViewClient() {
    //....
    override fun onPageFinished(view: WebView, url: String) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            view.evaluateJavascript("jsFunction();", null)
        } else {
            view.loadUrl("jsFunction();")
            //view.loadUrl("javascript:alert('Hamed');")
        }
    }
    //...
}

If your function returns a value (json ,..) and you need to capture the result, use this code :

view.evaluateJavascript("jsFunction();") {
    Log.i("TestJavaScript", "ValueCallBack=$it")
}
查看更多
▲ chillily
3楼-- · 2020-03-31 06:33

Wait til the page loading is finished and then execute webview.loadUrl("javascript:playVideo()");

private class MyCustomWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         view.loadUrl(url);
         return true;
    }
    public void onPageFinished(WebView view, String url) {
         view.loadUrl("javascript:playVideo()");
    }
}
查看更多
登录 后发表回答