I am trying to pass a simple String value from a native Android activity to my WebView activity and use DOM Manipulation to add that value to my HTML.
(我试图将一个简单的String值从本机Android活动传递到我的WebView活动,并使用DOM Manipulation将该值添加到我的HTML中。)
In the native activity I send the value to the WebView upon a button click:
(在本机活动中,单击按钮后,将值发送到WebView:)
public void onClick(View v) {
String s = nameText.getText().toString().trim();
Intent webIntent = new Intent(MainActivity.this, WebActivity.class);
startActivity(webIntent);
webIntent.putExtra("USERNAME", s);
}
In my WebView, I retrieve it and attempt to call my js function:
(在我的WebView中,我检索它并尝试调用我的js函数:)
public class WebActivity extends AppCompatActivity {
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
final String username = getIntent().getStringExtra("USERNAME");
myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.setWebContentsDebuggingEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
myWebView.loadUrl("javascript:hello(" + username + ")");
}
});
myWebView.loadUrl("file:///android_asset/www/index.html");
}
}
And finally, in Javascript I have my hello()
function:
(最后,在Javascript中,我有hello()
函数:)
var username = "";
function hello(name) {
username = name;
document.getElementById("userTextField").innerHTML = "Welcome " + username;
}
I thought this was all correct, but I always end up with Welcome null
after my HTML loads.
(我以为这都是正确的,但是在HTML加载后,我总是以Welcome null
结束。)
ask by Tony translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…