1

i know that to run a javascript function in webview we need to load it in loadUrl(). In my program everything works fine javascript gets called when i use it in loadUrl, but instead of running javascript on the same page, loadUrl("javascript:function()") vanishes my previous page and run this javascript "function()" in a totally new blank page..

for eg. i tried to fill a form automatically using command:

view.loadUrl("javascript:document.getElementById('password').value = 'my_passoword'");

what happens is, the page which consists of ID-'password' vanishes and a new blank page generates consisting of 'my_password' only

where is the problem?

phoenisx
  • 1,507
  • 17
  • 28
  • Try creating a function that sets the value of the input field and call that. Maybe Android does not like to evaluate the function in load url. – Bojan Kseneman May 21 '15 at 18:45
  • problem is it's not my site... I'm trying to make some kind of auto login system in my app using my college's website.. i cannot create my own function or change the website coding... – phoenisx May 21 '15 at 18:48
  • Why not? You can retrive the contents of the website, save jt to string, inject your JavaScript and load it in the webview – Bojan Kseneman May 21 '15 at 19:02
  • i think your way would work too, but it would be slow, as i have to login and navigate through two more pages and retrieve data.. as soon as possible. – phoenisx May 21 '15 at 19:17
  • Possible duplicate of [Android WebView always returns null for javascript getElementById on loadUrl](https://stackoverflow.com/questions/25602117/android-webview-always-returns-null-for-javascript-getelementbyid-on-loadurl) – rogerdpack Oct 10 '17 at 05:03

2 Answers2

2

Using loadUrl to run javascript loads different page

anonymous self-invoking function works fine.. i.e.

view.loadUrl("javascript:(function(){document.getElementById('password').value = 'sb14november';})()");

and as a loop around i think Bojan Kseneman answer will work too..

thanks to all!! :)

Community
  • 1
  • 1
phoenisx
  • 1,507
  • 17
  • 28
2

EDIT: This library is only for evaluating JavaScript and it created a new WebView instead of using an existing one :/

You can also try js evaluator library

jsEvaluator.evaluate("put your JavaScript code", new JsCallback() {
  @Override
  public void onResult(final String result) {
    // you get the result here (optional)
  }
});
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59