我正在嘗試編寫一個簡單的toast
程序。當我嘗試在HTML
內添加腳本時,它運行並能夠看到toast
。但是,當我將相同的script
代碼放在assert
文件夾(script.js)下的單獨文件中時,它無法注入javascript
。Android:如何將本地JavaScript文件加載到WebView
我支持API 15及以上版本。
這裏是代碼,我試圖注入script
。
myWebView = (WebView) findViewById(R.id.webviewid);
myWebView.loadDataWithBaseURL("file:///android_asset/",
"<html>" +
"<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">" +
"<style type=\"text/css\">\n" +
"@font-face {\n" +
" font-family: MyFont;\n" +
" src: url(\"file:///android_asset/fonts/myfont.ttf\")\n" +
"}\n" +
"body {\n" +
" font-family: MyFont;\n" +
" font-size: medium;\n" +
" text-align: justify;\n" +
"}\n" +
"</style>" +
"</head>" +
"<body>" +
"<input type=\"button\" value=\"Say hello\" onClick=\"showAndroidToast('Hello Android!')\" />" +
"<script type=\"text/javascript\" src=\"file:///android_asset/www/js/script.js\"/>" +
"</body>" +
"</html>", "text/html", "UTF-8", null);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.setWebViewClient(new MyWebViewClient());
這是我的javascript
代碼。 (的script.js)
function showAndroidToast(toast) {
Android.showToast(toast);
};
這裏是我Javascript
接口:
protected class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
我怎麼能注入javascript
文件?任何幫助表示讚賞。
我的項目結構是這樣的:
---
|
---- App
|
-----src
|
-----main
|
------asserts
| |
| ------fonts
| |
| ------www
| | |
| | ------js
| | |
| | ------script.js
|
------java
|
------res
貓日誌顯示:
E/Web Console﹕ Uncaught ReferenceError: showAndroidToast is not defined:13
這是最壞的情況......但我試圖注入腳本,這與互聯網連接工作。 – User12111111 2014-09-24 13:50:27
您是否正在檢查系統是否獲取腳本並且沒有將其返回空白或者它在源文件夾中找不到它 – 2014-09-24 13:52:05
這就是它的原因,它沒有加載腳本 – User12111111 2014-09-24 13:53:31