简体   繁体   中英

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.

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

2.change .js like this

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

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());

尝试这样的事情

webView.evaluateJavascript(yourFileAsString)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM