简体   繁体   English

如何将字符串值从活动传递给webView

[英]how to pass a string value to webView from an activity

Please tell me how to pass some string value from an activity to a webview. 请告诉我如何将一些字符串值从活动传递到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. 我在DashboardActivity中加载了带有加载URL的webview,我想将该活动的字符串值传递给javaScript window.onload函数使用的webview。 Please telle me a way to do so. 请告诉我一个这样做的方法。

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. 困难在于您希望在onload方法中执行操作。

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. 如果您确实需要在页面的onload方法上可访问的数据,则可以修改调用的url以包含查询数据(如果可能)。 Something like: 就像是:

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

and then use standard javascript to parse window.location.search to get the data. 然后使用标准的javascript来解析window.location.search来获取数据。

Finally, if you can't modify the URL for some reason, you can use a callback object to let the javascript get the value: 最后,如果由于某种原因无法修改URL,可以使用回调对象让javascript获取值:

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

and then when config your webView with this callback before loading the url: 然后在加载url之前使用此回调配置webView时:

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

and in the onload method of the page you could use: 在您可以使用的页面的onload方法中:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM