在 WebViewClient 中启用通用 JavaScript

发布于 2024-10-19 04:57:46 字数 2551 浏览 1 评论 0原文

在谷歌搜索答案时,似乎我并不是唯一一个遇到似乎无法解决的问题的人。

我成功地使用自定义 WebViewClient 创建了一个 WebView - 这使得我可以拥有一个进程对话框,并在无法加载 URL 时显示错误消息。

但这会给 JavaScript 带来一个问题。我正在加载的 URL 包含一些 JavaScript,它会更改某些 HTML 元素 CSS 样式(显示或隐藏元素)或在单击时重定向到另一个位置 - 或者甚至可能希望显示警告框。但通过使用 WebViewClient,这些都不起作用。

这就是我加载页面的方式:

public void loadUrl(String url)
{
    final ProgressDialog dialog = ProgressDialog.show(myActivity.this, "",  getString(R.string.loading), true);
            final WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setVerticalScrollBarEnabled(false);
            myWebView.setHorizontalScrollBarEnabled(false);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);                                         


            myWebView.setWebViewClient(new WebViewClient() 
            {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) 
                {
                    Toast.makeText(myActivity.this, url, Toast.LENGTH_SHORT).show(); //Debugging purposes
                if (url.endsWith(".mp4")) 
                {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.parse(url), "video/mp4");
                        view.getContext().startActivity(intent);  
                }
                else
                {                           
                        view.loadUrl(url);
                    }

                    return true;
                }

                public void onPageFinished(WebView view, String url) 
                {
                    //Toast.makeText(myActivity.this, "Oh no!", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }

                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
                {
                    Toast.makeText(myActivity.this, description, Toast.LENGTH_SHORT).show();
                    String summary = "<html><body><strong>" + getString(R.string.lost_connection) + "</body></html>";
                    myWebView.loadData(summary, "text/html", "utf-8");   
                }              

             }); //End WebViewClient

            myWebView.loadUrl(url);     
        }

这可能可以通过更智能的方式完成,但我在 Java 和 Android 开发方面都是新手...

我是否可以为 WebViewClient 启用 JavaScript? 删除 WebViewClient 解决了问题,但是当页面错误或完成加载时我无法捕获事件。

While searching for an answer in google, it seems that I'm not the only one stuck with a problem that seems impossible to solve.

I've managed to create a WebView with a custom WebViewClient - this makes it possible for me to have a processdialog and show an error message if an URL couldn't be loaded.

But this creates a problem with JavaScript. The URL I'm loading has some JavaScript which changes some HTML elements CSS styles (showing or hiding element) or redirects to another location onclick - or maybe even want's to show an alert box. But by using the WebViewClient none of those are working.

This is how I load a page:

public void loadUrl(String url)
{
    final ProgressDialog dialog = ProgressDialog.show(myActivity.this, "",  getString(R.string.loading), true);
            final WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setVerticalScrollBarEnabled(false);
            myWebView.setHorizontalScrollBarEnabled(false);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);                                         


            myWebView.setWebViewClient(new WebViewClient() 
            {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) 
                {
                    Toast.makeText(myActivity.this, url, Toast.LENGTH_SHORT).show(); //Debugging purposes
                if (url.endsWith(".mp4")) 
                {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.parse(url), "video/mp4");
                        view.getContext().startActivity(intent);  
                }
                else
                {                           
                        view.loadUrl(url);
                    }

                    return true;
                }

                public void onPageFinished(WebView view, String url) 
                {
                    //Toast.makeText(myActivity.this, "Oh no!", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }

                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
                {
                    Toast.makeText(myActivity.this, description, Toast.LENGTH_SHORT).show();
                    String summary = "<html><body><strong>" + getString(R.string.lost_connection) + "</body></html>";
                    myWebView.loadData(summary, "text/html", "utf-8");   
                }              

             }); //End WebViewClient

            myWebView.loadUrl(url);     
        }

This could probably be done in a smarter way, but I'm new at both Java and Android development...

Is it possible for me to enable the JavaScript for the WebViewClient at all?
Removing the WebViewClient solves the problem, but then I can't catch events when the page errors or is finished loading.

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

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

发布评论

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

评论(9

深府石板幽径 2024-10-26 04:57:46

我不知道您的确切问题是什么,但我可以毫无问题地启用 JavaScript 和自定义 WebViewclient

WebView vistaWeb = (WebView) findViewById(R.id.webview);
vistaWeb.setWebChromeClient(new MyCustomChromeClient(this));
vistaWeb.setWebViewClient(new MyCustomWebViewClient(this));
vistaWeb.clearCache(true);
vistaWeb.clearHistory();
vistaWeb.getSettings().setJavaScriptEnabled(true);
vistaWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

I don't know what your exact problem is, but i can enable the JavaScript and a custom WebViewclient without any problem:

WebView vistaWeb = (WebView) findViewById(R.id.webview);
vistaWeb.setWebChromeClient(new MyCustomChromeClient(this));
vistaWeb.setWebViewClient(new MyCustomWebViewClient(this));
vistaWeb.clearCache(true);
vistaWeb.clearHistory();
vistaWeb.getSettings().setJavaScriptEnabled(true);
vistaWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
情栀口红 2024-10-26 04:57:46

启用 JavaScript 的正确方法是添加以下两行:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

即使添加后不起作用,也请尝试添加以下行。

mWebView.getSettings().setDomStorageEnabled(true);

现在应该可以了。 :)

The proper way to enable JavaScript is by add the below two lines:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

Even if after adding its not working then try adding the below line.

mWebView.getSettings().setDomStorageEnabled(true);

Now It should work. :)

无戏配角 2024-10-26 04:57:46

尝试启用 JavaScript

WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(url);

Try this to enable javascript

WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(url);
渡你暖光 2024-10-26 04:57:46

在我的案例中发生了什么:我在申请时提供本地 html 文件,

    web.getSettings().setJavaScriptEnabled(true);
    web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

但后来我的网址停止工作。让 JS 和本地 href 都工作的解决方案是添加

    web.getSettings().setAllowFileAccess(true);
    web.getSettings().setAllowFileAccessFromFileURLs(true);

where

    web = (WebView) findViewById(R.id.embedded_web);

What happened in my case : I was serving local html files and when applying

    web.getSettings().setJavaScriptEnabled(true);
    web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

but then my urls stopped working. Solution to make both JS and local href work was to add

    web.getSettings().setAllowFileAccess(true);
    web.getSettings().setAllowFileAccessFromFileURLs(true);

where

    web = (WebView) findViewById(R.id.embedded_web);
£烟消云散 2024-10-26 04:57:46

这段代码恰好对我有用,我希望它可以帮助您和其他开发人员:

webview = findViewById(R.id.WebView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.loadUrl("www.example.com");

This code happen to works for me, I hope it can helps you and other developer:

webview = findViewById(R.id.WebView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.loadUrl("www.example.com");
蓬勃野心 2024-10-26 04:57:46

->您好,请尝试此代码此代码运行良好

->有关文档的更多信息,请访问 https://developer.android.com/guide/webapps /webview#java

->此链接在 2019 年 11 月运行良好,目前我不知道

->您的 XML 设计代码是

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


</LinearLayout>

->你的后端 Java 代码是

package com.developer.harshil.kaneria.webview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

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

        WebView myWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.loadUrl("https://github.com/Harshil-Kaneria");
    }
}

->这里是Java代码

WebSettings webSettings = myWebView.getSettings();

还有这个

webSettings.setJavaScriptEnabled(true);

->页面加载时允许 JavaScript 运行

->非常感谢您的阅读。

-> Hello Please Try This Code This Code Run Fine

-> For More Information of Documentation Please Visit https://developer.android.com/guide/webapps/webview#java

-> This Link Work Fine in Nov 2019 Currently I Don't Know

-> Your XML Code For Design is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


</LinearLayout>

-> And Your Java Code For Backend is

package com.developer.harshil.kaneria.webview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

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

        WebView myWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        myWebView.loadUrl("https://github.com/Harshil-Kaneria");
    }
}

-> Here in Java Code

WebSettings webSettings = myWebView.getSettings();

And This

webSettings.setJavaScriptEnabled(true);

-> It is Allow To JavaScript Run When Page is Load

-> Thanks A Lot For Read.

爱人如己 2024-10-26 04:57:46

“Javascript-URL”是否通过 shouldOverrideUrlLoading 路由?尝试检查一下,如果是这样,则为此类链接返回 false (以便 webview 处理该链接,而不是您的 WebViewClient)

Do "Javascript-URLs" get routed through shouldOverrideUrlLoading? Try checking that and if so, return false for links like that (so that the webview handles the link, not your WebViewClient)

半世蒼涼 2024-10-26 04:57:46

与 @mdelolmo 答案类似,但在 Kotlin 中:

    webview.setWebChromeClient(WebChromeClient())
    webview.setWebViewClient(WebViewClient())
    webview.clearCache(true)
    webview.clearHistory()
    webview.getSettings().setJavaScriptEnabled(true)
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true)

Similar to @mdelolmo answer, but in Kotlin:

    webview.setWebChromeClient(WebChromeClient())
    webview.setWebViewClient(WebViewClient())
    webview.clearCache(true)
    webview.clearHistory()
    webview.getSettings().setJavaScriptEnabled(true)
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true)
吹泡泡o 2024-10-26 04:57:46

如何启用以编程方式在其他答案中回答。但是,如果您的 webview 位于 nestedscrollview 中,某些 JavaScript 将无法正常工作。删除它并添加 webSettings.setJavaScriptEnabled(true);

How enable programmatically answered in other answers. But some javascripts not worked if your webview is in nestedscrollview. Remove it and add webSettings.setJavaScriptEnabled(true);

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