How to pass string value to webView from action

Please tell me how to pass a string value from an activity to a webview. I have a webview with a loaded URL in DashboardActivity, and I want to pass the string value from this action to the webview used by the javaScript window.onload function. Please ask me to do this.

+4
source share
2 answers

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!

+11
source

If an input field is selected on the loaded web page, you can try the following:

 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); 
+2
source

Source: https://habr.com/ru/post/1435000/


All Articles