1

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>

安卓代码

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

on Button Clicked 事件 java 脚本函数调用正确。但我无法在不单击按钮的情况下调用 java 脚本函数。

4

2 回答 2

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>
于 2012-06-04T10:55:11.570 回答
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 + "})()");
于 2012-06-04T10:30:24.880 回答