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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12490789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:19:16  来源:igfitidea点击:

how to pass a string value to webView from an activity

javascriptandroidwebview

提问by ssrp

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.

请告诉我如何将一些字符串值从活动传递到网络视图。我在 DashboardActivity 中有加载了 URL 的 webview,我想将一个字符串值从该活动传递给 javaScript window.onload 函数使用的 webview。请告诉我这样做的方法。

回答by Albin

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. Something like:

如果您确实需要可在页面的 onload 方法上访问的数据,则可以修改调用的 url 以包含查询数据(如果可能)。就像是:

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!

希望这可以帮助!

回答by TouchBoarder

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