user192632
user192632

Reputation: 266

how to call or mimic a javascript function inside a webview

I am making a hybrid app. I am using xamarin for android, pretty much the same as android. I have already figured out how to hook the phone's back button press. When pressed I want my app code to either mimic or call a javascript function that is part of the webpage that the webview is displaying. It is my web page, so I know the code that the webview is rendering. To be specific, I want to call a jquery slideToggle function on a page element when the phone's back button is pressed. Can that be done, and if so what would be the best approach? I'm hoping that someone here has had to do something just like this in the past. Thanks.

Upvotes: 0

Views: 333

Answers (1)

Rohit Vipin Mathews
Rohit Vipin Mathews

Reputation: 11787

I don't think webview supports JQuery, unless maybe you reference it.

The Xamarin android way of doing it is:

 webView.addJavascriptInterface(new JsObject(), "injectedObject");
 webView.loadData("", "text/html", null);
 webView.loadUrl("javascript:alert(injectedObject.toString())");

Source : Android.Webkit.WebView.AddJavascriptInterface Method

Also make sure you have enabled Javascript,

 web_view.Settings.JavaScriptEnabled = true;

You can show or hide the element by finiding it by id (document.FindElementById). Then you can set its display to block or none. Thus you can do it purely in Javascript.

Add on :

There are couple of problems with your method. To name a few -

  • on pressing of back button user expects a particular behavior and it should not be altered. This would not give a rich user experience.
  • if you are override ing the back button press then what about the navigation bar menu click.
  • JavaScript way of doing can cause security issues.

Upvotes: 1

Related Questions