Home » Android » javascript – Android WebView – access classes from one iframe inside another iframe

javascript – Android WebView – access classes from one iframe inside another iframe

Posted by: admin May 14, 2020 Leave a comment

Questions:

We have a native ios application, which displays a web view with HTML web page and two iframes. Inside those iframes, we display our articles from HTML files located in resources of the app. Inside the articles, there are often javascript scripts which operate on both articles at the same time. For example, make some part of the text bold. To do this, it lists all of the elements with a particular class and modify its CSS style.

$(".question").length()

would return the number of elements with class .question in both iframes on iOS, where it would only return elements from current iframe on Android. By “current” I mean the one that user interacted with to start the script.

We have a requirement to also release an android app.
It all went fine, until I tested an article, where javascript has to operate on both iframes. Unfortunately, it can only access elements from one iframe.

Is there any way I could make it work without changing the code of the javascripts attached to the articles? I have no authority there [besides it could be thousands of articles with plenty of custom javascripts to update].

Thank you

How to&Answers:

This is how i managed a similar case

webview.loadDataWithBaseURL("file:///android_asset/", your_html_as_string_here, "text/html", "utf-8", null);
webview.getSettings().setJavaScriptEnabled(true); // enable javascript
            webview.addJavascriptInterface(new WebViewJavaScriptInterface(getActivity()), "app");

and have to create a inner class and call same function as mentioned in javascript interface as ‘app.function1’

public class WebViewJavaScriptInterface {

        private Context context;

        /*
         * Need a reference to the context in order to sent a post message l
         */
        public WebViewJavaScriptInterface(Context context) {
            this.context = context;
        }

        /*
         * This method can be called from Android. @JavascriptInterface
         * required after SDK version 17.
         */

        @JavascriptInterface
        public void function1() {
            ll_translucent.setVisibility(View.VISIBLE);
        }

        /*
                * This method can be called from Android. @JavascriptInterface
                * required after SDK version 17.
                */
        @JavascriptInterface
        public void function2() {
            new CommonActions(getActivity()).showSnackToast(verticalSeekBar, "Purchase Episode to read Further");
        }
    }