如何将一个字符串值,从一个活动传递到web视图 [英] how to pass a string value to webView from an activity

查看:98
本文介绍了如何将一个字符串值,从一个活动传递到web视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我如何从一个活动到的WebView通过一些字符串值。我有在DashboardActivity加载网址的web视图,我想从活动使用的一个Javascript的window.onload函数的WebView传递一个字符串值。请Telle公司我的方式这样做。

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.

推荐答案

根据你的使用情况,也有完成此不同的方式。困难在于,你想要做的事情在onload方法。

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

如果你真的需要在页面的onload方法中的数据访问,您可以修改调用包括查询数据,如果可能的URL。是这样的:

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

,然后用标准的JavaScript解析window.location.search获取数据。

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

最后,如果您不能修改URL出于某种原因,你可以使用一个回调对象,让JavaScript的获得的价值:

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";
   }
}

,然后加载的URL,然后配置你的web视图与此回调时:

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

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

和中,你可以使用页面的onload方法:

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

var theString = stringGetter.getString();

希望这有助于!

Hope this helps!

这篇关于如何将一个字符串值,从一个活动传递到web视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆