There are various ways to achieve this, depending on your use case. The difficulty is that you want to do something in the onload method.
If after loading the page you can pass the line, you can use
String jsString = "javascript:addData('" + theString + "');"); webView.loadUrl(jsString);
if you really need the data available by the onload method on the page, you can change the url to include the request data, if possible. Sort of:
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 cannot change the URL for any reason, you can use the callback object so that javascript gets the value:
private class StringGetter { public String getString() { return "some string"; } }
and then when you set up 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!
source share