从Android WebViewClient中的网站下载Blob文件

Jon*_*zio 7 javascript android blob android-webview

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

window.open(fileUrl);
Run Code Online (Sandbox Code Playgroud)

浏览器中的一切都很好用,但是当在Webview组件内部实现时,新选项卡不会打开.

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

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Run Code Online (Sandbox Code Playgroud)

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"/>
Run Code Online (Sandbox Code Playgroud)

我也试着setDownloadListener去抓下载.另一种方法被替换为WebViewClient()for,WebChromeClient()但行为是相同的.

Kev*_*rez 12

好吧我在使用webview时遇到了同样的问题,我意识到WebViewClient无法像Chrome桌面客户端那样加载"blob URL",我使用Javascript接口解决了它.您可以按照以下步骤执行此操作,在此应用程序中使用minSdkVersion正常工作:17.首先,通过JS转换Base64字符串中的Blob URL数据.其次,将此字符串发送到Java类,最后以可用格式转换它,在这种情况下,我将其转换为".pdf"文件.

首先要做的事情.您必须设置您的webview,在我的情况下,我正在加载片段中的网页:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,让我们创建一个JavaScriptInterface.class,这个类将有我们的脚本将在我们的网页中执行.

public class JavaScriptInterface {
    private Context context;
    private NotificationManager nm;
    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', 'YOUR BLOB URL GOES HERE', 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()) {
            NotificationCompat.Builder b = new NotificationCompat.Builder(context, "MY_DL");
                    .setDefaults(NotificationCompat.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_file_download_24dp)
                    .setContentTitle("MY TITLE")
                    .setContentText("MY TEXT CONTENT");
            nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
            if(nm != null) {
                nm.notify(notificationId, b.build());
                Handler h = new Handler();
                long delayInMilliseconds = 5000;
                h.postDelayed(new Runnable() {
                    public void run() {
                        nm.cancel(notificationId);
                    }
                }, delayInMilliseconds);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

资料来源:

/sf/answers/2893796251/

/sf/answers/833116371/

/sf/answers/1397132901/

  • 在我的情况下,Blob 没有下载。当我在 android 的 webview 中单击下载时没有任何反应。请任何帮助。 (5认同)
  • 可以确认这个答案在2020年仍然有效(虽然我没有直接复制粘贴,而是采用了其中的方法)。如果您需要将 mime 类型和下载属性用于 PDF 以外的用途,您还可以将 mime 类型和下载属性从 javascript 传递到 Javascript 接口,例如 fileName = document.querySelector('a[href=\""+ blobUrl +"\"]') .getAttribute('下载'); (3认同)
  • 嘿。这是关于 Android Oreo (8.0) 在未提前配置通知渠道的情况下不显示通知的问题。抱歉,如果不清楚:) (2认同)
  • getBase64StringFromBlobUrl 方法中的脚本应该是网页上的脚本? (2认同)
  • 感谢您提供全面的答案,我遵循了它,但日志中也没有发生任何事情。 (2认同)