最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to pass a string value to webView from an activity - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited Sep 19, 2012 at 8:23 Bob 23k39 gold badges145 silver badges226 bronze badges asked Sep 19, 2012 at 8:11 ssrpssrp 1,2665 gold badges18 silver badges37 bronze badges 1
  • 1 Thank you for your corporation. I will. – ssrp Commented Sep 19, 2012 at 8:29
Add a ment  | 

2 Answers 2

Reset to default 16

Depending on your use case, there are different ways of acplishing 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!

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);
发布评论

评论列表(0)

  1. 暂无评论