javascript 从 Android WebViewClient 内的网站下载 Blob 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48892390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:20:03  来源:igfitidea点击:

Download Blob file from Website inside Android WebViewClient

javascriptandroidandroid-webviewblob

提问by Jonathan Brizio

I have an HTML Web page with a button that triggers a POST request when the user clicks on. When the request is done, the following code is fired:

我有一个 HTML 网页,其中有一个按钮,当用户单击时会触发 POST 请求。请求完成后,将触发以下代码:

window.open(fileUrl);

Everything works great in the browser, but when implement that inside of a Webview Component, the new tab doesn't is opened.

在浏览器中一切正常,但是在 Webview 组件内部实现时,新选项卡不会打开。

FYI: On my Android App, I have set the followings things:

仅供参考:在我的 Android 应用程序上,我设置了以下内容:

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

On the AndroidManifest.xmlI have the following permissions:

AndroidManifest.xml我有以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>

I try too with a setDownloadListenerto catch the download. Another approach was replaced the WebViewClient()for WebChromeClient()but the behavior was the same.

我也尝试使用 asetDownloadListener来捕捉下载。另一种方法被替换为WebViewClient()forWebChromeClient()但行为是相同的。

回答by Kevin Perez

Ok I had the same problem working with webviews, I realized that WebViewClient can't load "blob URLs" as Chrome Desktop client does. I solved it using Javascript Interfaces. You can do this by following the steps below and it works fine with minSdkVersion: 17. First, transform the Blob URL data in Base64 string using JS. Second, send this string to a Java Class and finally convert it in an available format, in this case I converted it in a ".pdf" file.

好的,我在使用 webviews 时遇到了同样的问题,我意识到 WebViewClient 无法像 Chrome 桌面客户端那样加载“blob URL”。我使用 Javascript 接口解决了它。您可以按照以下步骤执行此操作,它可以与 minSdkVersion 一起使用: 17. 首先,使用 JS 将 Blob URL 数据转换为 Base64 字符串。其次,将此字符串发送到 Java 类,最后将其转换为可用格式,在本例中,我将其转换为“.pdf”文件。

Before continue you can download the source code here :). The app is developed in Kotlin and Java. If you find any error, please let me know and I will fix it:

在继续之前,您可以在这里下载源代码:)。该应用程序是用 Kotlin 和 Java 开发的。如果您发现任何错误,请告诉我,我会修复它:

https://github.com/JaegerCodes/AmazingAndroidWebview

https://github.com/JaegerCodes/AmazingAndroidWebview

First things first. You have to setup your webview. In my case I'm loading the webpages in a fragment:

先说第一件事。您必须设置您的网络视图。在我的情况下,我正在加载片段中的网页:

public class WebviewFragment extends Fragment {
    WebView browser;
    ...

    // invoke this method after set your WebViewClient and ChromeClient
    private void browserSettings() {
        browser.getSettings().setJavaScriptEnabled(true);
        browser.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                browser.loadUrl(JavaScriptInterface.getBase64StringFromBlobUrl(url));
            }
        });
        browser.getSettings().setAppCachePath(getActivity().getApplicationContext().getCacheDir().getAbsolutePath());
        browser.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        browser.getSettings().setDatabaseEnabled(true);
        browser.getSettings().setDomStorageEnabled(true);
        browser.getSettings().setUseWideViewPort(true);
        browser.getSettings().setLoadWithOverviewMode(true);
        browser.addJavascriptInterface(new JavaScriptInterface(getContext()), "Android");
        browser.getSettings().setPluginState(PluginState.ON);
    }
}

Then, create a JavaScriptInterface class. This class contains the script that is going to be executed in our webpage.

然后,创建一个 JavaScriptInterface 类。这个类包含将要在我们的网页中执行的脚本。

public class JavaScriptInterface {
    private Context context;
    public JavaScriptInterface(Context context) {
        this.context = context;
    }

    @JavascriptInterface
    public void getBase64FromBlobData(String base64Data) throws IOException {
        convertBase64StringToPdfAndStoreIt(base64Data);
    }
    public static String getBase64StringFromBlobUrl(String blobUrl) {
        if(blobUrl.startsWith("blob")){
            return "javascript: var xhr = new XMLHttpRequest();" +
                    "xhr.open('GET', '"+ blobUrl +"', true);" +
                    "xhr.setRequestHeader('Content-type','application/pdf');" +
                    "xhr.responseType = 'blob';" +
                    "xhr.onload = function(e) {" +
                    "    if (this.status == 200) {" +
                    "        var blobPdf = this.response;" +
                    "        var reader = new FileReader();" +
                    "        reader.readAsDataURL(blobPdf);" +
                    "        reader.onloadend = function() {" +
                    "            base64data = reader.result;" +
                    "            Android.getBase64FromBlobData(base64data);" +
                    "        }" +
                    "    }" +
                    "};" +
                    "xhr.send();";
        }
        return "javascript: console.log('It is not a Blob URL');";
    }
    private void convertBase64StringToPdfAndStoreIt(String base64PDf) throws IOException {
        final int notificationId = 1;
        String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
        final File dwldsPath = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS) + "/YourFileName_" + currentDateTime + "_.pdf");
        byte[] pdfAsBytes = Base64.decode(base64PDf.replaceFirst("^data:application/pdf;base64,", ""), 0);
        FileOutputStream os;
        os = new FileOutputStream(dwldsPath, false);
        os.write(pdfAsBytes);
        os.flush();

        if (dwldsPath.exists()) {
            Intent intent = new Intent();
            intent.setAction(android.content.Intent.ACTION_VIEW);
            Uri apkURI = FileProvider.getUriForFile(context,context.getApplicationContext().getPackageName() + ".provider", dwldsPath);
            intent.setDataAndType(apkURI, MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf"));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            PendingIntent pendingIntent = PendingIntent.getActivity(context,1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            String CHANNEL_ID = "MYCHANNEL";
            final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel notificationChannel= new NotificationChannel(CHANNEL_ID,"name", NotificationManager.IMPORTANCE_LOW);
                Notification notification = new Notification.Builder(context,CHANNEL_ID)
                        .setContentText("You have got something new!")
                        .setContentTitle("File downloaded")
                        .setContentIntent(pendingIntent)
                        .setChannelId(CHANNEL_ID)
                        .setSmallIcon(android.R.drawable.sym_action_chat)
                        .build();
                if (notificationManager != null) {
                    notificationManager.createNotificationChannel(notificationChannel);
                    notificationManager.notify(notificationId, notification);
                }

            } else {
                NotificationCompat.Builder b = new NotificationCompat.Builder(context, CHANNEL_ID)
                        .setDefaults(NotificationCompat.DEFAULT_ALL)
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(android.R.drawable.sym_action_chat)
                        //.setContentIntent(pendingIntent)
                        .setContentTitle("MY TITLE")
                        .setContentText("MY TEXT CONTENT");

                if (notificationManager != null) {
                    notificationManager.notify(notificationId, b.build());
                    Handler h = new Handler();
                    long delayInMilliseconds = 1000;
                    h.postDelayed(new Runnable() {
                        public void run() {
                            notificationManager.cancel(notificationId);
                        }
                    }, delayInMilliseconds);
                }
            }
        }
        Toast.makeText(context, "PDF FILE DOWNLOADED!", Toast.LENGTH_SHORT).show();
    }
}

Then create an xml file in: ..\res\xml\provider_paths.xml

然后在:..\res\xml\provider_paths.xml 中创建一个 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Finally add this provider to your AndroidManifest.xml file

最后将此提供程序添加到您的 AndroidManifest.xml 文件中

<application ...>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
        <!-- some code below ->

Another alternative is using "Chrome Custom Tabs"

另一种选择是使用“Chrome 自定义标签”

Java:

爪哇:

CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    CustomTabsIntent customTabsIntent = builder.build();
    customTabsIntent.launchUrl(context, Uri.parse("https://stackoverflow.com"));

Kotlin:

科特林:

val url = "https://stackoverflow.com/"
            val builder = CustomTabsIntent.Builder()
            val customTabsIntent = builder.build()
            customTabsIntent.launchUrl(this, Uri.parse(url))

Sources:

资料来源:

https://stackoverflow.com/a/41339946/4001198

https://stackoverflow.com/a/41339946/4001198

https://stackoverflow.com/a/11901662/4001198

https://stackoverflow.com/a/11901662/4001198

https://stackoverflow.com/a/19959041/4001198

https://stackoverflow.com/a/19959041/4001198

回答by hoanngothanh

For who stilll can not download. I edited @Kevin method a little: Replace 'YOUR BLOB URL GOES HERE' with blobUrl

谁还不能下载。我稍微编辑了@Kevin 方法:用 blobUrl 替换“YOUR BLOB URL GOES HERE”

    public static String getBase64StringFromBlobUrl(String blobUrl) {
        if (blobUrl.startsWith("blob")) {
            return "javascript: var xhr = new XMLHttpRequest();" +
                    "xhr.open('GET', '" + blobUrl + "', true);" +
                    "xhr.setRequestHeader('Content-type','application/pdf');" +
                    "xhr.responseType = 'blob';" +
                    "xhr.onload = function(e) {" +
                    "    if (this.status == 200) {" +
                    "        var blobPdf = this.response;" +
                    "        var reader = new FileReader();" +
                    "        reader.readAsDataURL(blobPdf);" +
                    "        reader.onloadend = function() {" +
                    "            base64data = reader.result;" +
                    "            Android.getBase64FromBlobData(base64data);" +
                    "        }" +
                    "    }" +
                    "};" +
                    "xhr.send();";
        }
        return "javascript: console.log('It is not a Blob URL');";
    }