Android Webview JavaScript from Assets

Android WebView JavaScript from assets

Answer:

1. You MUST load the HTML into string:

private String readHtml(String remoteUrl) {
String out = "";
BufferedReader in = null;
try {
URL url = new URL(remoteUrl);
in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
out += str;
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out;
}


2. Load WebView with base URL:

String html = readHtml("http://mydomain.com/my.html");
mWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");

In this particular case you should have all .js files you want to use on the page to reside somewhere under "assets" folder of project. For example:

/MyProject/assets/jquery.min.js


3. In your remote html page you have to load .js and .css files that reside in your application like:

<script src="file:///android_asset/jquery.min.js" type="text/javascript"></script>

the same applies to all other local resources like images, etc. their path has to start with

file:///android_asset/

A WebView would first load the raw HTML you have provided as string, then pick .js, .css and other local resourses and then would load remote content.

Load CSS and JS files from assets folder in android webview

In android project

WebView myweb = FindViewById<WebView>(Resource.Id.webView1);
myweb.LoadUrl("file:///android_asset/index.html");

In index.html

<link href="style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>

And if you need to increase android webview performance and graphic change this properties

myweb.Settings.JavaScriptEnabled = true;
myweb.Settings.DisplayZoomControls = false;
myweb.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
myweb.SetLayerType(Android.Views.LayerType.Hardware, null);
}

if you are using android studio : view this link

if you need only js or css files view this Answers:

  • Load CSS JS from Assets folder
  • Android - How to load external javascript files within at runtime generated HTML data?
  • Android webview, loading javascript file in assets folder

How to load a js file from assets into webview when loading html from assets?

The issue has been resolved by enabling below properties.

if (Build.VERSION.SdkInt >= Build.VERSION_CODES.JellyBean)
{
webView.Settings.AllowUniversalAccessFromFileURLs = true;
webView.Settings.AllowFileAccessFromFileURLs = true;
}

Note: Keep the required JS files directly into Assets folder instead of keeping inner folders to keep JS files

-Thanks

Load external javascript file inside HTML file from android assets folder into WebView

There was an error in my javascript file. It works like I stated in my example. Sorry for wasting your time.

Android webview, loading javascript file in assets folder

I tried the same thing, loading a bookmarklet (the javascript code in your loadUrl() call) into a third-party page. My bookmarklet also depends on other assets (javascript and css files) which would not load with a file:///android_asset URL.

That's because the security context of the page is still that of, e.g., http://www.google.com, and that's not allowed access to file: URLs. You should be able to see the errors if you supply/override a WebChromeClient.onConsoleMessage().

I ended up with a kludge where I changed the bookmarklet's asset references to a bogus URL scheme, like:

asset:foo/bar/baz.js

and added a WebViewClient.shouldInterceptRequest() override which looks for those and loads them from assets using AssetManager.open().

One thing I don't like about this kludge is that the asset: scheme is open to any third-party HTML/Javascript on any page my view loads, giving them access to my app's assets.

One alternative, which I didn't try, would be to embed the sub-assets in the bookmarklet using data: URLs, but that can get unwieldy.

I'd much prefer it if there was a way to manipulate the security context of just the JS bookmarklet I'm loading in loadUrl(), but I can't find anything like that.

Here's a snippet:

import android.webkit.WebResourceResponse;
...
private final class FooViewClient extends WebViewClient
{
private final String bookmarklet;
private final String scheme;

private FooViewClient(String bookmarklet, String scheme)
{
this.bookmarklet = bookmarklet;
this.scheme = scheme;
}

@Override
public void onPageFinished(WebView view, String url)
{
view.loadUrl(bookmarklet);
}

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
if (url.startsWith(scheme))
try
{
return new WebResourceResponse(url.endsWith("js") ? "text/javascript" : "text/css", "utf-8",
Foo.this.getAssets().open(url.substring(scheme.length())));
}
catch (IOException e)
{
Log.e(getClass().getSimpleName(), e.getMessage(), e);
}

return null;
}
}

Android Web-View : Inject local Javascript file to Remote Webpage

There is a way to 'force' the injection of your local Javascript files from local assets (e.g., assets/js/script.js), and to circumvent the 'Not allowed to load local resource : file:///android_assets/js/script.js ...' issue.

It is similar to what described in another thread (Android webview, loading javascript file in assets folder), with additional BASE64 encoding/decoding for representing your Javascript file as a printable string.

I am using an Android 4.4.2, API level 19 Virtual Device.

Here are some code snippets:

[assets/js/script.js]:

    'use strict';

function test() {
// ... do something
}

// more Javascript

[MainActivity.java]:

    ...

WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();

webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

injectScriptFile(view, "js/script.js"); // see below ...

// test if the script was loaded
view.loadUrl("javascript:setTimeout(test(), 500)");
}

private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();

// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

myWebView.loadUrl("http://www.example.com");

...

load html from asset by html javascript button click on android webview

    WebView browser = (WebView) findViewById(webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebChromeClient(new WebChromeClient());
browser.loadUrl("file:///android_asset/www/index.html");
browser.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});

This will solve your problem.



Related Topics



Leave a reply



Submit