I am working with android application where this app will write file html in sd card. Then, load the file in web view. The apps can load html file but the javascript function in html file not working properly. Below is my code that I working on.
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();
}
}
}
Can someone help me in order make javascript function working in apps?