使用 LoadData 时在 WebView 中运行 Javascript

发布于 2024-12-11 17:14:39 字数 316 浏览 0 评论 0原文

我对 Android 开发非常陌生,我正在开发一个我认为简单的应用程序。我有一些 HTML 代码存储在原始资源文件夹中 - 该代码包含一些 Javascript。当我在 Google Chrome 中运行代码时,它运行良好 - 但是当我使用 loadData 函数将其加载到 webview 中时,它不会运行 Javascript。

我已启用 javascript:

mWebView.getSettings().setJavaScriptEnabled(true);

我需要能够在浏览器中运行此 Javascript - 有帮助吗?

I am very new to Android Dev and I am developing what I thought would be a simple app. I have some HTML code that is stored is the raw resources folder - the code includes some Javascript. When I run the code in Google Chrome it runs fine - however when I load it into the webview using the loadData function it doesn't run the Javascript.

I have enabled javascript with:

mWebView.getSettings().setJavaScriptEnabled(true);

I need to be able to run this Javascript within the browser - any help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

灰色世界里的红玫瑰 2024-12-18 17:14:40

尝试从代码中调用 JS 函数。像这样:

mWebView.loadUrl("javascript:myFunction()");

Try call JS function from code. Like this:

mWebView.loadUrl("javascript:myFunction()");
茶底世界 2024-12-18 17:14:40

加载的 HTML 数据是什么样子的?就我而言,我生成的原始 HTML 数据的格式为:

<html>
<head>
<style>..</style>
<script>..</script>
</head>
<body>...</body>
</html>

在普通浏览器中测试,一切按预期进行。然而,一旦我使用了 WebView.loadData,CSS 似乎可以被识别,但我发现 Javascript 不起作用。

发现对我有用的是将 Javascript 移动到外部文件(更具体地说,我使用内容提供程序将我需要的脚本放置到 asset/ 中。

<html>
<head>
<link rel="stylesheet" type="text/css" href="content://PATHTOSTYLESHEET" />
<script src="content://PATHTOJS"></script>
</head>
<body>...</body>
</html>

根据 Android webview 的 loadData 和 loadDataWithBaseURL 有什么区别 如果你设置一个合适的基数,听起来会更简单存储样式/脚本的 URL - 对本地存储的任何内容使用适当的 file://。

What does the loaded HTML data look like? In my case, the raw HTML data I generated was in the format:

<html>
<head>
<style>..</style>
<script>..</script>
</head>
<body>...</body>
</html>

Testing in a normal browser, things worked as expected. However, once I had used WebView.loadData, the CSS seemed to be recognized but I found that the Javascript was not working.

What found that worked for me was moving the Javascript to external files (more specifically I put the scripts I needed to assets/ using content providers.

<html>
<head>
<link rel="stylesheet" type="text/css" href="content://PATHTOSTYLESHEET" />
<script src="content://PATHTOJS"></script>
</head>
<body>...</body>
</html>

According to What is the difference between Android webview's loadData and loadDataWithBaseURL it sounds even more simple if you set a proper base URL which your style/scripts are stored - using the appropriate file:// for anything you store locally.

妞丶爷亲个 2024-12-18 17:14:40

我正在跟进@Cobaia上面的答案,还有另一个(我认为)有用的功能:

由于我需要在测试和调试时不断更改嵌入的HTML,所以我决定在开发过程中从本地Web服务器获取原始页面页面并将其传递给 webView,如下所示:

String url, str;

str = getFromURL(url);
webView.loadDataWithBaseURL("blarg://ignored", str, "text/html", "UTF-8", "");

其中 getFromURL() 定义为:

    public String getFromURL(String urlToRead) {
      URL url;
      HttpURLConnection conn;
      BufferedReader rd;
      String result = "";
      char[] chunk = new char[8192];
      int blen = chunk.length;
      int amt;      

      try {
         url = new URL(urlToRead);
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");


         rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         while ((amt = rd.read(chunk, 0, blen)) > 0) {
             result += new String(chunk, 0, amt);
          }
         rd.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }

请注意,我必须创建一个特殊的控制器(我正在使用 CodeIgniter)以允许从服务器将文件作为文本文件下载。

希望这个提示也能帮助其他人!

I am following up on @Cobaia's answer above, with another (I think) useful feature:

Since I need to keep changing the embedded HTML while testing and debugging, I decided to grab the raw page from my local web server during the development of the page and pass it to the webView as follows:

String url, str;

str = getFromURL(url);
webView.loadDataWithBaseURL("blarg://ignored", str, "text/html", "UTF-8", "");

where getFromURL() is defined as:

    public String getFromURL(String urlToRead) {
      URL url;
      HttpURLConnection conn;
      BufferedReader rd;
      String result = "";
      char[] chunk = new char[8192];
      int blen = chunk.length;
      int amt;      

      try {
         url = new URL(urlToRead);
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");


         rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
         while ((amt = rd.read(chunk, 0, blen)) > 0) {
             result += new String(chunk, 0, amt);
          }
         rd.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }

Note that I had to create a special controller (I'm using CodeIgniter) to allow downloading the file as a text file from the server.

Hope this hint helps others too!

与君绝 2024-12-18 17:14:40

上述解决方案对我不起作用,因为我正在加载包含 HTML 的字符串而不是单独的 HTML 文件。字符串中的 HTML 引用了 asset/www/ 中的 JavaScript。有效的是使用 mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);

请参阅下面的完整示例。该示例创建一个 Web 视图,从字符串加载 HTML,然后调用单独的 JavaScript 文件中的函数。该功能仅显示警报。

public class MainActivity extends Activity{

    private WebView mWv;

    private static final String HTML_AS_STRING = 
            "<!DOCTYPE html>"                                   +
            "<html>"                                            +
            "<head>"                                            +
            "</head>"                                           +
            "<body>"                                            +

            "<p>Just some text in a paragraph.</p>"             +
            "<div align=\"center\" style=\"color:#0000FF\">"    +
            "<h3>This is a heading in a div element</h3>"       +
            "<p>This is some text in a div element.</p>"        +
            "</div>"                                            +

            "<font size=\"4\" color=\"0000FF\">"                +
            "This is some sized and colored text."              +
            "</font>"           
                                                                +
            "<script src=\"index.js\"></script>"                +

            "</body>"                                           +
            "</html>";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mWv = (WebView)findViewById(R.id.webview);      
        mWv.getSettings().setJavaScriptEnabled(true);

        mWv.setWebViewClient(new WebViewClient(){
            @Override  
            public void onPageFinished(WebView view, String url){  
                mWv.loadUrl("javascript:showAlert()");
            }  
        });
        mWv.setWebChromeClient(new WebChromeClient());

        mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);      
    }
}

index.js(assets/www/ 中的单独文件):

function showAlert() {
    alert("A simple alert!");
}

The above solutions did not work for me because I was loading a string that held the HTML instead of a separate HTML file. The HTML in the string referenced JavaScripts that were in assets/www/. What worked was to use mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);

See below for a full example. The example create a webview, loads the HTML from the string, and then calls a function in a separate JavaScript file. The function simply shows an alert.

public class MainActivity extends Activity{

    private WebView mWv;

    private static final String HTML_AS_STRING = 
            "<!DOCTYPE html>"                                   +
            "<html>"                                            +
            "<head>"                                            +
            "</head>"                                           +
            "<body>"                                            +

            "<p>Just some text in a paragraph.</p>"             +
            "<div align=\"center\" style=\"color:#0000FF\">"    +
            "<h3>This is a heading in a div element</h3>"       +
            "<p>This is some text in a div element.</p>"        +
            "</div>"                                            +

            "<font size=\"4\" color=\"0000FF\">"                +
            "This is some sized and colored text."              +
            "</font>"           
                                                                +
            "<script src=\"index.js\"></script>"                +

            "</body>"                                           +
            "</html>";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mWv = (WebView)findViewById(R.id.webview);      
        mWv.getSettings().setJavaScriptEnabled(true);

        mWv.setWebViewClient(new WebViewClient(){
            @Override  
            public void onPageFinished(WebView view, String url){  
                mWv.loadUrl("javascript:showAlert()");
            }  
        });
        mWv.setWebChromeClient(new WebChromeClient());

        mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);      
    }
}

index.js (A separate file in assets/www/):

function showAlert() {
    alert("A simple alert!");
}
再见回来 2024-12-18 17:14:39

试试这个:

webView.loadDataWithBaseURL("blarg://ignored", getData(), "text/html",
“utf-8”,“”);

Try this:

webView.loadDataWithBaseURL("blarg://ignored", getData(), "text/html",
"utf-8", "");

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文