【问题标题】:Android webview - JavaScript callback not working?Android webview - JavaScript 回调不起作用?
【发布时间】:2017-09-24 18:50:46
【问题描述】:

我正在使用 WebView 在 android 应用程序上显示网页。 https://developer.android.com/guide/webapps/webview.html

单击 HTML 中的按钮后,我可以成功进入 Android 类 WebAppInterface(来自示例)并显示“Toast”警报,但尝试回调定义的 javacsript 函数在我的网页中不起作用。

这是网页代码:(Android.html)

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        if (typeof Android != 'undefined') 
            Android.showToast(toast);       


    }

    function ChangeColor()
    {
        document.body.style.background = 'pink';
    }
</script>

这是 Android 应用的 MainActivity 的代码。它加载 url 并显示它。

public class MainActivity extends AppCompatActivity {

    WebView m_Webview;

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

        m_Webview = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = m_Webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        m_Webview.setWebViewClient(new WebViewClient());
        m_Webview.loadUrl("android.html");


        WebView webView = (WebView) findViewById(R.id.webview);
        webView.addJavascriptInterface(new WebAppInterface(this,webView), "Android");
    }
}

这是 Android 应用上的 WebAppInterface:

public class WebAppInterface {

    Context mContext;
    WebView mView;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c,WebView w) {
        mContext = c;
        mView = w;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        mView.loadUrl("javascript:ChangeColor()");
    }
}

在 toast 显示后,JavaScript 函数 ChangeColor 没有被调用。

更多参考请见:https://stackoverflow.com/a/14145116/7751339

谢谢!

【问题讨论】:

    标签: javascript android html webview hybrid-mobile-app


    【解决方案1】:

    解决方案是像这样使用“发布”功能:

    public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
          //  WebView Web = new WebView(mContext);
           // mView.getSettings().setUserAgentString("Android WebView");
            mView.post(new Runnable() {
                public void run() {
                    mView.loadUrl("javascript:ChangeColor()");
                }
            });
        }
    

    同样在 KitKat 和转发上,您需要使用 evaluateJavascript

    mView.evaluateJavascript("ChangeColor();",null);
    

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      • 2017-10-06
      • 2014-07-31
      • 1970-01-01
      相关资源
      最近更新 更多