从android webview调用javascript函数?

时间:2013-06-24 16:18:03

标签: javascript video webview

我尝试直接从我的应用程序(webview.apk)调用javascript函数,为了启动一个自动播放html5视频剪辑的脚本,我试图在webview loadURL之后添加它,但没有运气。< / p>

也许有人可以看看代码。我错过了什么?谢谢!

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 个答案:

答案 0 :(得分:5)

等待页面加载完成,然后执行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()");
    }
}

答案 1 :(得分:0)

用于调用jsFunction的Kotlin代码并获取结果:

  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');")
                }
        }
       //...
      }

如果您的函数返回一些值(json,..),并且您需要捕获回调,请使用以下代码:

 view.evaluateJavascript("jsFunction();") {
                        Log.i("TestJavaScript", "ValueCallBack=$it")
                    }