[英]Android studio load javascript function from file in sd card
我正在使用android應用程序,此應用程序將在sd卡中寫入html文件。 然后,在Web視圖中加載文件。 該應用程序可以加載html文件,但是html文件中的javascript功能無法正常運行。 以下是我正在處理的代碼。
public class WriteWebPage extends AppCompatActivity {
Button btn;
WebView wb;
private String fileName = "SampleFile.html";
private String filePath = "/sdcard/";
File myExternalFile;
String myData = "";
@SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_webpage);
btn = findViewById(R.id.btn);
wb = findViewById(R.id.wb);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
wb.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
wb.getSettings().setJavaScriptEnabled(true);
wb.loadUrl("file://" + myExternalFile);
wb.setWebChromeClient(new WebChromeClient());
wb.setWebViewClient(new WebViewClient());
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
String a = "asd12sf";
String html = "<html><body>" +
"<h3>Hello World</h3>" +
"<p>" + a + "</p>" +
"<input type= 'button' value='button' onClick='dialog()'/>" +
"<script language='javascript'>" +
"function dialog(){" +
"AndroidFunction.openAndroidDialog();}" +
"</script>" +
"</body></html>";
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(html.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
wb.loadUrl("file://"+myExternalFile);
}
});
if(isExternalStorageAvailable()){
myExternalFile = new File(getExternalFilesDir(filePath), fileName);
}
}
private static boolean isExternalStorageAvailable(){
String extStorageState = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(extStorageState)){
return true;
}
return false;
}
private class MyJavaScriptInterface{
Context mContext;
MyJavaScriptInterface(Context c){
mContext = c;
}
@JavascriptInterface
public void dialog(){
AlertDialog.Builder myDialog = new AlertDialog.Builder(WriteWebPage.this);
myDialog.setTitle("Danger!");
myDialog.setMessage("Hi");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
}
有人可以幫助我使javascript功能在應用中正常工作嗎?
您正在調用openAndroidDialog()函數,該函數未在Javascript接口中的任何位置定義。 您必須調用dialog()函數
您的html
String html = "<html><body>" +
"<h3>Hello World</h3>" +
"<p>" + a + "</p>" +
"<input type= 'button' value='button' onClick='dialog()'/>" +
"<script language='javascript'>" +
"function dialog(){" +
"AndroidFunction.openAndroidDialog();}" +
"</script>" +
"</body></html>";
應該
String html = "<html><body>" +
"<h3>Hello World</h3>" +
"<p>" + a + "</p>" +
"<input type= 'button' value='button' onClick='dialog()'/>" +
"<script language='javascript'>" +
"function dialog(){" +
"AndroidFunction.dialog();}" +
"</script>" +
"</body></html>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.