A button in my WebView
is used to go back using the history.back()
JavaScript call. I do not understand much of JavaScript, but after a bit of searching I found that we can use the addJavascriptInterface()
method of a WebView
.
Now, I intend to finish my Activity when the button is clicked. I landed up having something of this sort:
public class MyActivity extends Activity {
private static final String sTag = "MyActivity";
private WebView mWebContent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browser_page);
mWebContent = (WebView) findViewById(R.id.webContent);
mWebContent.getSettings().setJavaScriptEnabled(true);
mWebContent.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebContent.getSettings().setBuiltInZoomControls(true);
mWebContent.addJavascriptInterface(new JavaScriptInterface(), "history"); //history.back();
Bundle extras = getIntent().getExtras();
if (extras != null) {
mWebContent.loadUrl(extras.getString("URL"));
}
}
public class JavaScriptInterface {
JavaScriptInterface() {
}
public void back() {
Log.v(sTag, "back pressed");
MyActivity.this.finish();
}
}
}
But unfortunately when the button is pressed the Activity doesn't finish, neither do I get anything in the Log.
Here is the html for the button :
<a href="javascript:void(0);">
<img src="images/btn-go-back.png" onClick="history.back();" border="0" />
</a>
What am I doing wrong?
Thanks in advance.
Edit : Just wanted to clear the fact that changing the html is not an option for me. I have no power over the the html code :). I have to handle it in the application.
Edit: Tried changing history.back()
to window.history.back()
(locally), still no change.
Edit : I was experimenting by locally loading html conent and found out that if I change history.back()
to say something like android_app.back()
and register my JavaScriptInterface
by the nameandroid_app
it works fine. Why is that? Does that mean that we can't use history
to register an interface? Does the developer docs mention this?