Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView - access classes from one iframe inside another iframe

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

like image 882
Krystian Avatar asked Mar 09 '17 14:03

Krystian


1 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");
        }
    }
like image 100
g7pro Avatar answered Oct 26 '22 04:10

g7pro