2
我正在使用WebView在Android應用程序上顯示網頁。 https://developer.android.com/guide/webapps/webview.htmlAndroid webview - JavaScript回調不起作用?
從HTML點擊一個按鈕後,我能順利拿到到Android類WebAppInterface(從例子),並顯示「吐司」的警報,但在嘗試回調到我的網站定義的一個javacsript功能-page不起作用。
這是網頁的代碼:(Android.html)
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
if (typeof Android != 'undefined')
Android.showToast(toast);
}
function ChangeColor()
{
document.body.style.background = 'pink';
}
</script>
這是Android應用在MainActivity的代碼。它加載網址並顯示它。
public class MainActivity extends AppCompatActivity {
WebView m_Webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_Webview = (WebView) findViewById(R.id.webview);
WebSettings webSettings = m_Webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
m_Webview.setWebViewClient(new WebViewClient());
m_Webview.loadUrl("android.html");
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this,webView), "Android");
}
}
這是在Android應用程式的WebAppInterface:
public class WebAppInterface {
Context mContext;
WebView mView;
/** Instantiate the interface and set the context */
WebAppInterface(Context c,WebView w) {
mContext = c;
mView = w;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
mView.loadUrl("javascript:ChangeColor()");
}
}
JavaScript函數ChangeColor是越來越顯示敬酒後不獲取調用。
更多參考請參見:https://stackoverflow.com/a/14145116/7751339
謝謝!