I place the .html (which consist of the .js web link) file in the assest, now I am trying to load url
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.loadUrl("file:///android_asset/anim1.html");
Here I am unable to play the .js file, waiting for the positive response.
The WebView method to load our file takes a URI , so we need to access the HTML file using that URI . Since we stored it in the assets folder, we can access it using file:///android_asset/{file_name} . Now let's load that file in our MainActivity .
WebView allows you to bind JavaScript code to Android code through an interface. To do this, we must use the addJavaScriptInterface() method, which is passed the class that provides the interface for JS, and the name that will be used to display the instance in JS (for example, “AndroidFunction“).
First of all, I think it's unlikely that you really want to be accessing HTML and JavaScript files from the assets, as the assets cannot (and shouldn't) be updated once the app has been packaged and signed. This means, that with your HTML and JavaScript in the assets, you cannot update them. The approach to solve that problem is to save the HTML and JavaScript in the internal or the external storage, and use it from there.
Secondly, if you use that approach I just explained, you cannot any longer use the WebView.loadUrl()
method, but instead you will need to use the WebView.loadDataWithBaseUrl()
method. Like this:
webView.loadDataWithBaseURL("http://some_url/", "some_data", "text/html", "utf-8", null);
Then, "some_data" will be tried loaded as an HTML page, as seen in this previous SO answer. When it tries to load a JavaScript resource, like /scripts/lib.js
, it will be resolved to http://some_url/scripts/lib.js
, and the WebView will try to load that resource. Of course it cannot, and that is why you (in Java) will need to extend the WebViewClient
class, and provide an implementation for the shouldInterceptRequest(WebView wv, String url)
method.
When any resource is tried to be fetched in the web page, ´shouldInterceptRequest´ will be called, and its return value used as the resource.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With