如何从片段中的webview调用JavaScript?

时间:2015-04-21 06:44:25

标签: javascript android android-fragments webview

下面的代码,我用来加载片段中的webview,我想从webview调用JavaScript函数,但是下面的代码不起作用。

public class MainActivity extends ActionBarActivity
{
    public void loadUrlInWebView(String url,String positon)
        {
        WebViewFragment fragment =  new WebViewFragment();
        Bundle data = new Bundle();
        data.putString("url",url);
        fragment.setArguments(data);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
        }

        var url ="javascript:mobileApp.openLoginMenu()";
            loadUrlInWebView(url,null);
}

public class WebViewFragment extends Fragment{
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
        url = getArguments().getString("url");
        View rootView = inflater.inflate(R.layout.activity_main, container, false);
        webView = (WebView) rootView.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JsInterface(getActivity()),"AndroidJSObject");
        webView.loadUrl(url);
        webView.setWebViewClient(new WebViewClient()
        {
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
            view.loadUrl(url);
            return true;
            }
        });
        return rootView;
        }
}

2 个答案:

答案 0 :(得分:2)

要将javascript调用到Android,您可以拨打addJavascriptInterface()

有关详细说明,请点击此链接Building Web Apps in WebView

要记住的是,

如果要从android方法调用javascript方法,则应在调用addJavascriptInterface()时提供的字符串名称上调用方法名称,正好在您的情况下在你的JavaScript中

AndroidJSObject.yourmethod

内部javascript文件。

答案 1 :(得分:0)

如果android:targetSdkVersion >=17

@SuppressLint("JavascriptInterface")方法

中添加onCreated

class InJavaScript {
        @JavascriptInterface
        public void runOnAndroidJavaScript(String status) {
            collectionStatus.setCollectionStatus(status);
        }
    }

小心@JavasscriptInterface。