简体   繁体   中英

How to load local HTML with JavaScript in Android WebView?

I have coded a game in HTML and JavaScript. I had loaded the HTML file locally into the WebView but it had not loaded the JavaScript. I was wondering how I could get the HTML to use the JavaScript. Any help is greatly appreciated.

Try this code.. This code works for.. Hope it will be helpfull to u also.

WebView webView;
        webView = (WebView) findViewById(R.id.wbView);
        webView.getSettings().setPluginsEnabled (true);
        webView.getSettings().setJavaScriptEnabled (true);

You can check here: http://developer.android.com/resources/tutorials/views/hello-webview.html

in order to get a general perspective of js with webview and more specifically:

mWebView.getSettings().setJavaScriptEnabled(true);

Hope this helps!

you can try this :

String html = "<html><body>Hello, World!</body></html>";
String mime = "text/html";
String encoding = "utf-8";
WebView myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);

Just load HTML file URI like this:

webView.loadUrl("file://" + getContext().getExternalCacheDir() + "/editor.html");

Hope it can help you!

    binding.webview.settings.javaScriptEnabled=true
    binding.webview.loadUrl("file:///android_asset/GeneralCF.html")

    binding.your_view.setOnClickListener {
        // load js on click button
        binding.webview.loadUrl("javascript:myFunction(\"$str_name\")")
    }

index.js

function myFunction(str_name)
{
document.getElementById("demo").innerHTML = str_name;
}

GeneralCF.html

        <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="">
        <meta name="Keywords" content="">
        <meta name="Description" content="">
        <title>Document</title>
        <script src="index.js"></script>
    
    </head>
    <body>
    
    <h1>This is my first webpage</h1>
    
    <p id="demo">A Paragraph.</p>
    
    <button type="button" onclick="myFunction()">Try it</button>
    
    
    </body>
    </html>

String encodedHtml = Base64.encodeToString(html_code_goes_here_string_object.getBytes(), Base64.NO_PADDING); webView.loadData(encodedHtml, "text/html", "base64");

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