Android:调用JavaScript函数中的问题

时间:2012-06-04 09:53:15

标签: javascript android html5 webview

JavaScript函数

    <!DOCTYPE html>
   <html>
   <head>
  <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width; user-scalable=0;" />
    <title>My HTML</title>
   </head>
     <body>
        <h1>MyHTML</h1>
       <p id="mytext">Hello!</p>

        function callFromActivity(msg){
           alert("Hello! I am an alert box!");
          document.getElementById("mytext").innerHTML = msg;
       }


   </script>

  </body>
  </html>

Android代码

myWebView.loadUrl("file:///android_asset/mypage.html");
String msgToSend = "message";
myWebView.loadUrl("javascript:callFromActivity(\"" + msgToSend
            + "\")");

on Button Click事件javascript函数调用正确。但是如果没有按钮点击,我就无法调用java脚本功能。

2 个答案:

答案 0 :(得分:1)

您的javascript格式错误。你应该把它放在这样的标签

<script type="text/javascript">
    //your JS
</script>

所以,你的代码看起来就是那个

 <script type="text/javascript">
 function callFromActivity(msg){
    alert("Hello! I am an alert box!");
   document.getElementById("mytext").innerHTML = msg;
 }
 </script>

答案 1 :(得分:0)

试试这个,

     String msgToSend = "message";
     String js = "msg = "+msgToSend+";"
                 +"function callFromActivity(msg){"
                 +"alert('Hello! I am an alert box!');"
                 +"document.getElementById('mytext').innerHTML = msg;";

      view.loadUrl("javascript:(function(){" + js + "})()");