Search code examples
javascriptandroidwebviewassets

JavaScript Working When Access From Internet But Not Responding When Access Page From Folder Assets On WebView Android


I try to access this page url : DEMO FACE TRACKER using android webview. And I using this code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    wv = (WebView) findViewById(R.id.webView);
    wv.setWebChromeClient(new WebChromeClient());
    wv.setWebViewClient(new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    });
    wv.getSettings().setJavaScriptEnabled(true);
    wv.addJavascriptInterface(new WebAppInterface(this), "Android");
    wv.loadUrl("http://auduno.github.io/clmtrackr/clm_image.html");
}

and IT WORKS!

But when I copy all of page (include javascript) to local, and access it form assets folder then app return NOT RESPONDING.

this is code that I use to access local assets:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    wv = (WebView) findViewById(R.id.webView);
    wv.setWebChromeClient(new WebChromeClient());
    wv.setWebViewClient(new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    });
    wv.getSettings().setJavaScriptEnabled(true);
    wv.addJavascriptInterface(new WebAppInterface(this), "Android");
    wv.loadUrl("file:///android_asset/index.html");
}

For information, all of assets (scripts, css, etc) except media has combined into single page and when I access from browser (on my computer) its working, but not in android webview.

whether on android has special permission for this? please help :) thank you.


Solution

  • Most likely you have pathing issue. It might not be loading from where you think it does. Try adding to see

            @Override
            public void onLoadResource(WebView view, String resUrl) {
                super.onLoadResource(view, resUrl);
                Log.d(LOG_TAG,"Loading " + resUrl);
            }
    

    Add setAllowUniversalAccessFromFileURLs to address javascript security issue when loading from file.

    wv.getSettings().setAllowUniversalAccessFromFileURLs(true);