最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

android - Calling JavaScript function in WebView - Stack Overflow

programmeradmin2浏览0评论

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?

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()");

The HTML file is:

<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>

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?

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()");

The HTML file is:

<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>
Share Improve this question edited Mar 7, 2013 at 21:09 user1521536 asked Mar 7, 2013 at 20:52 RachitRachit 7,0313 gold badges18 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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().

发布评论

评论列表(0)

  1. 暂无评论