preamble
We are at the WebView
setup side of the equation.
At first glance an obvious comment, but if you don't need JavaScript
, don't enable JavaScript
, then you don't get JavaScript
popup's. I'm assuming you DO need JavaScript
(remember it may be XSS vulnerable) and want to do what you can to disable the popups that can inevitably follow.
INFO:
WebViewClient. Override this behavior of your WebView
, e.g. so links open within your WebView
.
WebChromeClient lets you handle Javascript's alert()
and other functions.
OP(1)setJavaScriptCanOpenWindowsAutomatically(true)
is usually blocked only when done outside of an event handler.
OP = Original Post ;O).
Let's setup a senario
This is how I setup my normal webview
:
WebView webView = (WebView) this.findViewById(R.id.webView1);//CustomWebView ?
WebSettings webView_settings = webView.getSettings();
//by setting a WebClient to catch javascript's console messages :
WebChromeClient webChromeClient = new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(TAG, cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId() );
return true;
}
});
webView_settings.setDomStorageEnabled(true);
WebViewClient webViewClient = new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setTitle(view.getTitle());
//do your stuff ...
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file"))
{
// Keep local assets in this WebView.
return false;
}
}
});
//webView.setWebViewClient(new HelpClient(this));//
webView.setWebChromeClient(webChromeClient);
webView.setWebViewClient(webViewClient);
webView.clearCache(true);
webView.clearHistory();
webView_settings.setJavaScriptEnabled(true);//XSS vulnerable set to false ?
webView_settings.setJavaScriptCanOpenWindowsAutomatically(true);//set to false ?
webView.loadUrl("file:///android_asset/connect.php.html");//load something
OP(2) Let's block what we can
From @markproxy If you extend WebChromeClient
, you can override its onJsAlert()
method and block the built-in handler for alerts. While you're at it, you will probably want to block calls to the confirm()
and prompt()
:
WebChromeClient webChromeClient = new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
result.cancel();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
result.cancel();
return true;
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
result.cancel();
return true;
}
};
webView.setWebChromeClient(webChromeClient);
setJavaScriptEnabled(boolean true/false);
– Sophistic