how to pass a string value to webView from an activity

12,610

Solution 1

Depending on your use case, there are different ways of accomplishing this. The difficulty lies in that you want to do things in the onload method.

If it is possible to pass in the string after the page is loaded, you could use

String jsString = "javascript:addData('" + theString + "');");
webView.loadUrl(jsString);

if you really need the data accessible on the onload method of the page, you could modify the url called to to include query data if possible. Something like:

String urlWithData = yourUrl + "?data=" + theString;
webView.loadUrl(urlWithData);

and then use standard javascript to parse window.location.search to get the data.

Finally, if you can't modify the URL for some reason, you can use a callback object to let the javascript get the value:

private class StringGetter {
   public String getString() {
       return "some string";
   }
}

and then when config your webView with this callback before loading the url:

webView.addJavascriptInterface(new StringGetter(), "stringGetter");

and in the onload method of the page you could use:

var theString = stringGetter.getString();

Hope this helps!

Solution 2

If a input field is selected on the loaded webpage you could try this:

String pasteData = "a string value to paste into the webview"    
String javaScript = "javascript:document.activeElement.setAttribute('value','"+pasteData+"');";

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.requestFocus(View.FOCUS_DOWN);
mWebView.loadUrl(javaScript);
Share:
12,610
ssrp
Author by

ssrp

An undergraduate in University of Moratuwa, srilanka, studying as a computer science engineer till 2013 and having graduated as an engineer. Interested in developing software, android, VB, and web designing.

Updated on July 22, 2022

Comments

  • ssrp
    ssrp almost 2 years

    Please tell me how to pass some string value from an activity to a webview. I have the webview with loaded URL in the DashboardActivity and I want to pass a string value from that activity to the webview used by a javaScript window.onload function. Please telle me a way to do so.

    • ssrp
      ssrp over 11 years
      Thank you for your corporation. I will.