Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

javascript - 将数据从本机活动传递到WebView并返回null(Passing data from native activity to WebView returning null)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...