在Android的webview中调用Javascript方法 [英] Calling Javascript method from within webview in Android

查看:168
本文介绍了在Android的webview中调用Javascript方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试从webview中调用html页面中定义的JavaScript方法。函数没有被调用,并且在日志中没有看到任何错误。



这是html文件。

 < /头> 
< body>
< script type =text / javascript>
函数callJS(){
$ .ajax({url:http://10.0.2.2:5010});
}
< / script>
< / body>
< / html>

这就是android中一个Activity中的Java代码

  WebView webView = new WebView(this); 
webView.getSettings()。setJavaScriptEnabled(true);
webView.loadUrl(file:///android_asset/temp.html);
webView.loadUrl(javascript:callJS());

不知道如何调试。当我在html中的body标签中添加一个 onload = callJS()时,我看到正在进行的远程调用。所以,它看起来像我的HTML是好的,它正在加载到webview。但是,webview无法直接调用javascript方法。

解决方案

您应该在加载页面时执行javascript函数

p>

  webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view,String url){
webView.loadUrl(javascript:callJS());
}
});

当您将 onload = callJS()意味着当页面加载时,javascript函数将被调用。
对于调试,您可以将console.log(您的文本在这里)放在您的javascript函数中,并且您将在android studio日志中获取它。 (通常使用标记 I / chromium )。否则,您可以在Android上使用Chrome进行远程调试。这里的文档 https://developer.chrome.com/devtools/docs/remote-debugging


I am trying to call a javascript method defined in a html page from within webview. Function is not being called, and I don't see any errors in the log.

This is html file.

    </head>
    <body>
    <script type="text/javascript">
        function callJS(){
            $.ajax({url:"http://10.0.2.2:5010"});
        }
    </script>
    </body>
    </html>

And this is the Java code in a Activity in android

    WebView webView = new WebView(this);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("file:///android_asset/temp.html");
    webView.loadUrl("javascript:callJS()");

Not sure how to debug this. When I add a onload=callJS() in body tag in html, I see the remote call being made. So, it looks like my HTML is fine,and it is being loaded into webview. However, webview is not able to call javascript method directly.

解决方案

You should execute the javascript function when the page is loaded

webView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:callJS()");
    }
});

When you put onload=callJS() means that the javascript function will be call when page is load. For debugging, you can put console.log("your text here") in your javascript function and you will get it in your android studio log. (Commonly with the tag I/chromium). Otherwise, you can use Remote Debugging on Android with Chrome. The documentation here https://developer.chrome.com/devtools/docs/remote-debugging.

这篇关于在Android的webview中调用Javascript方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆