Marco Ripamonti
Marco Ripamonti

Reputation: 99

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

I'm trying to load an external JavaScript file into an HTML file. Both are placed in the assets folder.

This is my htmlTest.html file:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    <script src="test.js"></script>
</head>

<body>

    <script type="text/javascript">

        func();


    </script>

</body>

And this is my test.js file:

function func(){
    $(document).ready(function () {
        $('#EDIFICI').children().click(function () {
            alert($(this).attr('id'));
        });

    });
}   

Both files are located in the root of the assets folder. I load htmlTest.html into my WebView like this:

wv.loadUrl("file:///android_asset/htmlTest.html");  

If I put JavaScript code inline directly inside the HTML page it works, but it doesn't when I link an external JavaScript file.

Upvotes: 2

Views: 2683

Answers (5)

MirlvsMaximvs
MirlvsMaximvs

Reputation: 1483

This worked for me:

 <head>
        <script type="text/javascript" src="file:///android_asset/xxxxx.js"></script>
</head>

And xxxxx.js is in the assets folder.

In the code

WebView.enableSlowWholeDocumentDraw();
        oWebView.clearCache(true);
        oWebView.setPadding(0, 0, 0, 0);
        oWebView.setInitialScale(1);
        oWebView.getSettings().setUseWideViewPort(true);
        oWebView.getSettings().setLoadWithOverviewMode(true);
        oWebView.getSettings().setSupportZoom(true);
        oWebView.getSettings().setBuiltInZoomControls(true);
        oWebView.setScrollbarFadingEnabled(false);
        oWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        oWebView.getSettings().setJavaScriptEnabled(true);
        oWebView.setWebViewClient(new WebViewClient());

Upvotes: 1

touhid udoy
touhid udoy

Reputation: 4442

1.on onCreate add getSettings().setJavaScriptEnabled(true)

2.change .js like this

<head>
    <script type="text/javascript" src="test.js"></script>
</head>

Upvotes: 1

Marco Ripamonti
Marco Ripamonti

Reputation: 99

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

Upvotes: 0

Khaustov Kirill
Khaustov Kirill

Reputation: 69

Try to add your script as follow

<html>
  <head>
    <script type="text/javascript" src="test.js"></script>
  </head>

And add test.js file to folder with html

Upvotes: 0

Khaustov Kirill
Khaustov Kirill

Reputation: 69

Try something like this

webView.evaluateJavascript(yourFileAsString)

Upvotes: 0

Related Questions