从Android MainActivity访问js变量 [英] Accessing js variable from android MainActivity

查看:124
本文介绍了从Android MainActivity访问js变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想作为一个android应用程序访问一个webapp,因为我所做的只是使用webview调用该webapp的url。 Webapp包含一个js变量,我想要访问该变量到android MainActivity中,我如何通过使用android MainActivity来访问和赋值js变量,该变量在不同的webapp中。以下是我的MainActivity的代码片段,

  @Override 
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

mWebview =新的WebView(this);

mWebview.getSettings()。setJavaScriptEnabled(true);
mWebview.getSettings()。setDatabaseEnabled(true);
mWebview.getSettings()。setLoadWithOverviewMode(true);

mWebview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
mWebview.setScrollbarFadingEnabled(false);
mWebview.loadUrl(http://www.mywebapp.com);

setContentView(mWebview);


}

我的主要问题是如何访问和

//在js或html中调用方法
Android.getImageUrl(text);

//在主要活动中添加此行。
webView.addJavascriptInterface(new JavaScriptInterface(this),Android);

// js value get in this method。(add this method in activity)
public class JavaScriptInterface {
Context mContext;

JavaScriptInterface(Context c){
mContext = c;
}

@JavascriptInterface
public void getImageUrl(String text){
// js value get here。
}
}
}


I want to access a webapp as a android app, for this what I have done is simply calling url of that webapp by using webview. Webapp contains one js variable, I want to access that variable into androids MainActivity, how can I access and assign value to js variable which is in different webapp by using android MainActivity. Following is my code snippet for MainActivity,

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWebview = new WebView(this);

        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setDatabaseEnabled(true);
        mWebview.getSettings().setLoadWithOverviewMode(true);

        mWebview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        mWebview.setScrollbarFadingEnabled(false);
        mWebview.loadUrl("http://www.mywebapp.com");

        setContentView(mWebview);


    }

My main question is how to access and assign a value to js variable through androids MainActivity which is in different app/html?

解决方案

     // Call method in js or html
 Android.getImageUrl("text");

    // add this line in main activity.    
     webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

    // js value get in this method.(add this method in activity)
    public class JavaScriptInterface {
                Context mContext;

                JavaScriptInterface(Context c) {
                    mContext = c;
                }

                @JavascriptInterface
                public void getImageUrl(String text) {
        // js value get here.
                    }
                }
            }

这篇关于从Android MainActivity访问js变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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