JavaScript 无法在 Android Webview 中运行?

发布于 2024-12-06 13:29:13 字数 1543 浏览 0 评论 0原文

我正在尝试制作一个相对简单的 iOS 应用程序的 Android 版本,该应用程序使用 webview、一些按钮,然后依赖于对 CMS 的 javascript 调用。

但我陷入了开发的早期阶段:webview 无法使用 javascript 运行。我读过很多关于如何在 Android webview 中启用 JS 的文章,但到目前为止还没有运气。

下面是我的一些代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.setWebViewClient(new HelloWebViewClient()
    {
        @Override  
        public void onPageFinished(WebView view, String url)  
        {  
            //Calling an init method that tells the website, we're ready 
            mWebView.loadUrl("javascript:m2Init()");
            page1(mWebView);
        }  
    });
  mWebView.loadUrl("http://my_url/mobile/iphone//app.php");  
}

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        mWebView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public void page11(View view)
{
    mWebView.loadUrl("javascript:m2LoadPage(1)");
}

我在这里做错了什么? 该 URL 在我的 iOS 应用程序和浏览器中运行良好。 但我的应用程序中没有!

请告诉我这是显而易见的事情......

I'm trying to make an Android version of a relativly simple iOS app that uses a webview, some buttons and then relies on javascript calls to a CMS.

But I'm stuck at a pretty early point of development: The webview doesn't function with javascript.I've read a lot of posts about how to enable JS in an Android webview, but no luck so far.

Below is some of my code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.setWebViewClient(new HelloWebViewClient()
    {
        @Override  
        public void onPageFinished(WebView view, String url)  
        {  
            //Calling an init method that tells the website, we're ready 
            mWebView.loadUrl("javascript:m2Init()");
            page1(mWebView);
        }  
    });
  mWebView.loadUrl("http://my_url/mobile/iphone//app.php");  
}

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        mWebView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public void page11(View view)
{
    mWebView.loadUrl("javascript:m2LoadPage(1)");
}

What am I doing wrong here?
The URL is working perfectly in my iOS app, and in a browser.
But not in my app!

Please tell me it's something obvious...

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

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

发布评论

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

评论(12

So要识趣 2024-12-13 13:29:13

固定的!
在错误的刺激下,我发现我需要

设置setDomStorageEnabled(true)

为 webview 设置

。感谢您的帮助斯蒂芬:)

FIXED!
Spurred on by the error, I found out that I needed to set

setDomStorageEnabled(true)

for the webview settings.

Thanks for your help Stephan :)

请爱~陌生人 2024-12-13 13:29:13

万一 Android 上的 WebView 无法正常工作,我总是尝试确保我设置了这些疯狂的标志,例如,

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);
    webSettings.setSupportZoom(true);
    webSettings.setDefaultTextEncodingName("utf-8");

我想知道为什么默认情况下没有设置这些标志,现在谁会期望没有 javascript 内容的网页,以及有 javascript 有什么用除非指定,否则当 DOM 不可用时启用。希望有人已经将此作为错误或改进/功能请求提交,并且猴子正在努力解决它。

然后有一些不推荐使用的东西在某个地方腐烂,就像这样:

webView.getSettings().setPluginState(PluginState.ON);

所有这些都是为了在应用程序内加载网页。

在 iOS 上,一切都如此简单 - Swift 3.0

private func openURLWithInAppBrowser(urlString:String) {
    guard let url = URL(string:urlString) else {
        return
    }
    let sfSafari = SFSafariViewController(url:url)
    present(sfSafari, animated: true, completion: nil)
}

In case something with WebView on Android does not work, I always try to make sure I set these crazy flags such as,

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);
    webSettings.setSupportZoom(true);
    webSettings.setDefaultTextEncodingName("utf-8");

I wonder why these are not set by Default, who would expect webpages without javascript content nowadays, and whats the use having javascript enabled when DOM is unavailable unless specified. Hope someone filed this as a bug or improvement/feature-request already and the monkeys are working on it.

and then there is deprecated stuff rotting somewhere, like this:

webView.getSettings().setPluginState(PluginState.ON);

All this for loading webpages inside app.

On iOS, its all so simple - Swift 3.0

private func openURLWithInAppBrowser(urlString:String) {
    guard let url = URL(string:urlString) else {
        return
    }
    let sfSafari = SFSafariViewController(url:url)
    present(sfSafari, animated: true, completion: nil)
}
顾忌 2024-12-13 13:29:13

主要是,这三行足以使 Javascipt 在 webView 中工作...

webSetting.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());

如果之后它也不起作用,那么也添加下面的行。

webSettings.setDomStorageEnabled(true);

实际上,您需要 setJavaScriptEnabled() 和 setWebChromeClient(new WebChromeClient()) 才能使 JavaScript 正常工作。如果您只使用 webSetting.setJavaScriptEnabled(true);那么就不行了。

Mainly, these three lines will be enough to make the Javascipt work in webView...

webSetting.setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());

If it's not working after that also, then add below line also.

webSettings.setDomStorageEnabled(true);

Actually, you need both setJavaScriptEnabled() and setWebChromeClient(new WebChromeClient()) to make the JavaScript work. If you will use only webSetting.setJavaScriptEnabled(true); then it won't work.

感情洁癖 2024-12-13 13:29:13

在 webview 中加载 javascript

webView.getSettings().setDomStorageEnabled(true);

Loading javascript in webview

webView.getSettings().setDomStorageEnabled(true);
微凉徒眸意 2024-12-13 13:29:13

在 MainActivity.java 中添加以下代码行

它帮助我启用 js

  webSetting.setJavaScriptEnabled(true);
  webView.setWebChromeClient(new WebChromeClient());
  webView.setWebViewClient(new WebViewClient());

不要忘记 AndroidManifest 文件中的此权限。

<uses-permission Android:name="Android.permission.INTERNET" />

Add the following lines of code in your MainActivity.java

It helped me to enable js

  webSetting.setJavaScriptEnabled(true);
  webView.setWebChromeClient(new WebChromeClient());
  webView.setWebViewClient(new WebViewClient());

do not forget about this permission in AndroidManifest file.

<uses-permission Android:name="Android.permission.INTERNET" />
梦言归人 2024-12-13 13:29:13

您是否在清单中启用了正确的互联网权限?否则一切看起来都很好。您是否也在实际的 Android 手机上测试过这段代码?不仅仅是在模拟器上?

这是一个关于稍微不同的方法的很好的教程。您可能想尝试一下,看看它是否适合您。

Did you enable the right internet permission in the manifest? Everything looks fine otherwise. By any chance, have you also tested this code on an actual Android phone? And not just on the emulator?

Here is a good tutorial on a slightly different approach. You may want to try that one to see if it works for you.

归途 2024-12-13 13:29:13

该视频 (http://youtu.be/uVqp1zcMfbE) 给了我让它发挥作用的提示。
关键是将 htmljs 文件保存在 Android assets/ 文件夹中。
然后您可以通过以下方式轻松访问它们:

webView.loadUrl("file:///android_asset/your_page.html");

This video (http://youtu.be/uVqp1zcMfbE) gave me the hint to make it work.
The key is to save your html and js files in the Android assets/ folder.
Then you can easily access them via:

webView.loadUrl("file:///android_asset/your_page.html");
a√萤火虫的光℡ 2024-12-13 13:29:13

如果您使用 Kotlin,您可以使用以下方法让 JavaScript 正常工作:

webView.apply {
     loadUrl(
         "file:///android_asset/frm/my_html_landing_page_here.html"
     )

     settings.javaScriptEnabled = true
     settings.domStorageEnabled = true
 }

同时确保您的整个文件夹位于 Assets 文件夹内(这包括 HTML、Javascript 和其他所需文件)

If you are in Kotlin you can use the following method to get the JavaScript working :

webView.apply {
     loadUrl(
         "file:///android_asset/frm/my_html_landing_page_here.html"
     )

     settings.javaScriptEnabled = true
     settings.domStorageEnabled = true
 }

Also make sure that your entire folder is inside the Assets folder (this includes HTML, Javascript and other file needed)

如梦 2024-12-13 13:29:13

Xamarin Android也存在同样的问题,即WebView不执行任何Javascript。按照 @computingfreak 的回答:

        this.SetContentView(Resource.Layout.activity_main);

        var webView = this.FindViewById<WebView>(Resource.Id.webView);

        var webSettings = webView.Settings;
        webSettings.JavaScriptEnabled = true;
        webSettings.DomStorageEnabled = true;
        webSettings.LoadWithOverviewMode = true;
        webSettings.UseWideViewPort = true;
        webSettings.BuiltInZoomControls = true;
        webSettings.DisplayZoomControls = false;
        webSettings.SetSupportZoom(true);
        webSettings.DefaultTextEncodingName = "utf-8";

奇怪的是,他们将所有 setter 方法更改为属性,除了 SetSupportZoomSupportZoom 保留为 getter :/

Xamarin Android also has the same problem that WebView does not execute any Javascript. Follow @computingfreak answer:

        this.SetContentView(Resource.Layout.activity_main);

        var webView = this.FindViewById<WebView>(Resource.Id.webView);

        var webSettings = webView.Settings;
        webSettings.JavaScriptEnabled = true;
        webSettings.DomStorageEnabled = true;
        webSettings.LoadWithOverviewMode = true;
        webSettings.UseWideViewPort = true;
        webSettings.BuiltInZoomControls = true;
        webSettings.DisplayZoomControls = false;
        webSettings.SetSupportZoom(true);
        webSettings.DefaultTextEncodingName = "utf-8";

Weirdly enough they changed all setter methods to properties except SetSupportZoom and SupportZoom stays as getter :/

猫九 2024-12-13 13:29:13

只需允许您的 WebView 运行 JS,就这么简单:

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

Just permit your WebView to run JS, simple like that:

WebView web=(WebView)findViewById(R.id.web);
web.getSettings().setJavaScriptEnabled(true);
热情消退 2024-12-13 13:29:13

要在 WebView 中启用 javascript 弹出窗口,需要设置 webChromeClient 并覆盖 openFileChooser 方法。

    mWebview.setWebChromeClient(new WebChromeClient(){
        // For Android 4.1+
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);

            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(acceptType);

            startActivityForResult(Intent.createChooser(i, "SELECT"), 100);
        }

        // For Android 5.0+
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mUploadMessageArr != null) {
                mUploadMessageArr.onReceiveValue(null);
                mUploadMessageArr = null;
            }

            mUploadMessageArr = filePathCallback;

            Intent intent = fileChooserParams.createIntent();

            try {
                startActivityForResult(intent, 101);
            } catch (ActivityNotFoundException e) {
                mUploadMessageArr = null;

                Toast.makeText(activity,"Some error occurred.", Toast.LENGTH_LONG).show();

                return false;
            }

            return true;
        }
    });

并按如下方式处理 onActivityResult:

@SuppressLint("NewApi")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (mUploadMessage == null) return;
        Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

    else if (requestCode == 101) {
        if (mUploadMessageArr == null) return;
        mUploadMessageArr.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
        mUploadMessageArr = null;
    }

}

To enable javascript popups in WebView its necessary to set webChromeClient and override openFileChooser methods.

    mWebview.setWebChromeClient(new WebChromeClient(){
        // For Android 4.1+
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;

            Intent i = new Intent(Intent.ACTION_GET_CONTENT);

            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(acceptType);

            startActivityForResult(Intent.createChooser(i, "SELECT"), 100);
        }

        // For Android 5.0+
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mUploadMessageArr != null) {
                mUploadMessageArr.onReceiveValue(null);
                mUploadMessageArr = null;
            }

            mUploadMessageArr = filePathCallback;

            Intent intent = fileChooserParams.createIntent();

            try {
                startActivityForResult(intent, 101);
            } catch (ActivityNotFoundException e) {
                mUploadMessageArr = null;

                Toast.makeText(activity,"Some error occurred.", Toast.LENGTH_LONG).show();

                return false;
            }

            return true;
        }
    });

And handle the onActivityResult as below:

@SuppressLint("NewApi")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (mUploadMessage == null) return;
        Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }

    else if (requestCode == 101) {
        if (mUploadMessageArr == null) return;
        mUploadMessageArr.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
        mUploadMessageArr = null;
    }

}
迷路的信 2024-12-13 13:29:13

如果以上没有帮助尝试在 WebViewClient.onPageFinished 侦听器中添加延迟

override fun onPageFinished(view: WebView?, url: String?) {
            Handler().postDelayed({
                //update your view with js here
                super.onPageFinished(view, url)
            }, 1000)
        }

If nothing above helped try to add delay in WebViewClient.onPageFinished listener

override fun onPageFinished(view: WebView?, url: String?) {
            Handler().postDelayed({
                //update your view with js here
                super.onPageFinished(view, url)
            }, 1000)
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文