Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  121] [ 4]  / answers: 1 / hits: 19681  / 13 Years ago, thu, august 25, 2011, 12:00:00

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?


More From » android

 Answers
43

After a lot of searching and asking I have finally arrived at the conclusion that you cannot add a java script interface, using addJavascriptInterface (Object obj, String interfaceName), with the interface name as history (or perhaps any javascript keyword).



Maybe this is written somewhere in the developer docs or manual, but I couldn't find it though.


[#90420] Wednesday, August 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leifw

Total Points: 88
Total Questions: 103
Total Answers: 103

Location: France
Member since Thu, May 6, 2021
3 Years ago
;