Skip to content

Instantly share code, notes, and snippets.

@kingori
Last active July 14, 2017 04:32
Show Gist options
  • Save kingori/24ed51e889b73936316b60d6acf73714 to your computer and use it in GitHub Desktop.
Save kingori/24ed51e889b73936316b60d6acf73714 to your computer and use it in GitHub Desktop.
public class WebViewActivity extends Activity {
WebView wv;
LinkedList<JsResult> jsResults = new LinkedList<>();
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wv);
WebView.setWebContentsDebuggingEnabled(true);
wv = findViewById(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true);
WebChromeClient wc = new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
jsResults.add(result);
new AlertDialog.Builder(WebViewActivity.this).setMessage(message)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
jsResults.remove(result);
result.cancel();
}
}).show();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
jsResults.add(result);
new AlertDialog.Builder(WebViewActivity.this).setMessage(message)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
jsResults.remove(result);
result.cancel();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
jsResults.remove(result);
result.confirm();
}
})
.show();
return true;
}
};
wv.setWebChromeClient(wc);
wv.loadData("<html><head><script>function myAlert() { \n\r alert('haha'); \n\r}\n\r\n\r" +
" window.setTimeout(myAlert, 500);</script></head><body>aaa</body></html>","text/html", "utf-8");
}
@Override
protected void onDestroy() {
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
wv.destroy();
for(JsResult jsResult: jsResults ) {
jsResult.cancel();
}
super.onDestroy();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment