2012-11-08 115 views
0

我有JS其返回值如何從javascript返回值

function sendDisplay() 
{ 
var dis = alert(reader.dom.find('controls_contents_container').style.display); 
return dis; 
} 
在android系統

我嘗試設置的返回值設定在Android的變量,所以我可以在android系統

public class MainActivity extends DroidGap { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     CookieManager.setAcceptFileSchemeCookies(true); 
     super.onCreate(savedInstanceState); 
     super.setIntegerProperty("splashscreen", R.drawable.cover); 
     super.loadUrl("file:///android_asset/www/index.html",1500); 

    } 


    @Override 
    public void onBackPressed() { 
     super.loadUrl("javascript:alert(sendDisplay())"); 


    } 


} 
一個如果else語句

當我在loadUrl方法中提醒時,它的JS值顯示值。但我不知道如何將該值設置爲android變量。

TQ

+0

要做Java到JavaScript的通信,我想你需要製作一個[自定義PhoneGap插件](http://docs.phonegap.com/en/2.1.0/guide_plugin-development_index.md.html ),它使用Android後端[Plugin對象](http://docs.phonegap.com/en/2.1.0/guide_plugin-development_android_index.md.html)在JavaScript中運行,以捕獲JavaScript發送的消息。 – apsillers

+0

這是http://stackoverflow.com/questions/3298597/how-to-get-return-value-from-javascript-in-webview-of-android的副本 – Keith

回答

4

看看上Binding Javascript Code to Android Code谷歌的導向部。我還將發佈一個簡短的總結在這裏:

首先,您需要建立一個Java類:

public class JavaScriptInterface { 
    Context mContext; 

    /** Instantiate the interface and set the context */ 
    JavaScriptInterface(Context c) { 
     mContext = c; 
    } 

    /** Show a toast from the web page */ 
    public void showToast(String toast) { 
     Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
    } 
} 

然後,你需要這個類的一個實例添加到您的WebView爲JavaScript接口:

WebView webView = (WebView) findViewById(R.id.webview); 
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); 

最後,你可以把它用 「Android.showToast(其他)」 從JavaScript,或者你可以調用的JavaScript從Java代碼:

loadUrl("javascript:Android.showToast(whatever)"); 

在顯示Toast消息的情況下,這有點多餘。但希望你明白這個主意。