在WebView,Android上评估javascript值

时间:2010-11-10 21:42:17

标签: javascript android webview handler android-webview

我打开一个页面有

的网页浏览页面
<script type="text/javascript">
  var addToBasketDisabled=false;
  var iPhoneStatus=""; 
  function GetStatus()
  {
    return iPhoneStatus;//Master Pagelerde tanımlı
  }

  var path = "http://www.yemeksepeti.com/App_Themes/Default_tr-TR/images/IPhone/";             
  function PreLoadDisabledButton()
  {
    var image = new Image();   
    image.src=path + "Iphone-button-ekle-pasif.png";
  }

  function DisableAddButton()
  {
    addToBasketDisabled= true;
    var buttonObject = document.getElementById("ctl00_AddToBasket");
    buttonObject.src = path + "Iphone-button-ekle-pasif.png";
  }

  function EnableAddButton()
  {
    addToBasketDisabled= false;
    var buttonObject = document.getElementById("ctl00_AddToBasket");
    buttonObject.src = path + "Iphone-button-ekle.png";
  }

  function OnAddButtonClick()
  {
    if(addToBasketDisabled)
    {
      return false;
    }
    DisableAddButton();
    var validateValue= ValidateInput(); 
    if(!validateValue)
    {
      EnableAddButton();
      return false;
    }
  }
  PreLoadDisabledButton();
</script>

这些javascript 当我按下webview上的按钮时,我必须阅读“iPhoneStatus”值并关闭webview屏幕并确定结果。

我在.java类中编写了这些代码

mWebView = (WebView) findViewById(R.id.webview);

WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);

mWebView.setWebChromeClient(new MyWebChromeClient());

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

mWebView.loadUrl(feedurl);
final class DemoJavaScriptInterface
{

  DemoJavaScriptInterface()
  {
  }

  public void clickOnAndroid()
  {
    mHandler.post(new Runnable()
    {
      public void run()
      {
        mWebView.loadUrl("javascript: GetStatus()");
      }
    });
  }
}

final class MyWebChromeClient extends WebChromeClient
{
  public void onCloseWindow(WebView window)
  {
    window.destroy();
  }
  public boolean onJsAlert(WebView view, String url, String message, JsResult result)
  {
    Log.i("log ", message);
    result.confirm();
    return true;
  }
}

但它永远不会进入onJsAlert方法,有没有办法评估GetStatus()的值

由于

1 个答案:

答案 0 :(得分:3)

步骤1:让您的demo对象实现一些接受GetStatus()值作为参数的方法。

步骤2:致电mWebView.loadUrl("javascript:..."),其中...是一段URL编码的Javascript源代码,调用GetStatus()并将该值传递给您的demo对象