在WebView中调用JavaScript函数 [英] Calling JavaScript function in WebView

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

问题描述

我知道这个问题已被多次询问,我检查了所有解决方案,并研究了一切。但是,这根本不适合我。

I know this question has been asked many times and I have checked all the solutions and researched everything. However, this is simply not working for me.

我不知道我做错了什么。有人可以帮帮我吗?

I don't know what I am doing wrong. Can someone please help me out?

我在我的 WebView 中加载一个本地html文件,然后调用JavaScript功能:

I am loading a local html file in my WebView and then calling the JavaScript function:

wv.loadUrl("file:///android_asset/sample.html");
wv.getSettings().setJavaScriptEnabled(true);
JavascriptInterface javasriptInterface = new JavascriptInterface(MyActivity.this);
wv.addJavascriptInterface(javasriptInterface, "MyInterface");
wv.loadUrl("javascript:loadpath()");

HTML文件是:

<html>
<head>
</head>

<body>
<script type="text/javascript">
    function callDoSomething() {
        // Do something
    }

    function loadpath() {
        // Is not called no matter whatever operation I do here. Just printing a string, setting variable, android callback anything.
        document.write("Hi");
        document.getElementById('img').src = "path.png";
    }
</script>

<form name="myForm" action="FORM">
    <img src=""  alt="Autofill" /><br>
    <input type="button" value="Submit" onClick="callDoSomething()" />
</form>

</body>
</html>


推荐答案

loadUrl()是异步的。您过早地调用第二个 loadUrl() 方式。您需要等到页面加载,可能是使用 WebViewClient 并观察 onPageFinished()

loadUrl() is asynchronous. You are calling your second loadUrl() way too soon. You need to wait until your page is loaded, perhaps by using a WebViewClient and watching for onPageFinished().

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

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