santosh gore
santosh gore

Reputation: 329

How to call JavaScript from webview in fragment?

Below code, I am using to load webview in fragment and I want to call JavaScript function from webview but below code is not working.

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

Upvotes: 0

Views: 2190

Answers (2)

Simba Liu
Simba Liu

Reputation: 3

if android:targetSdkVersion >=17

add @SuppressLint("JavascriptInterface") in onCreated method

and

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

watch out @JavasscriptInterface.

Upvotes: 0

BBdev
BBdev

Reputation: 4942

To call a javascript into android you can call addJavascriptInterface().

For more explanation please follow this link Building Web Apps in WebView.

And the thing to keep in mind is,

When you want to call an android method from javascript method, the method name should be called on the string name you have provided while calling addJavascriptInterface() precisely in your case something like this in your javascript

AndroidJSObject.yourmethod

Inside javascript file.

Upvotes: 3

Related Questions