Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从Android WebViewClient内的网站下载Blob文件_Javascript_Android_Android Webview_Blob - Fatal编程技术网

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

Javascript 从Android WebViewClient内的网站下载Blob文件,javascript,android,android-webview,blob,Javascript,Android,Android Webview,Blob,我有一个HTML网页,其中有一个按钮,当用户单击时,该按钮会触发POST请求。请求完成后,将触发以下代码: window.open(fileUrl); 浏览器中的一切都很好,但在Webview组件中实现这些功能时,新选项卡不会打开 仅供参考:在我的Android应用程序上,我设置了以下内容: webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setSupportMultipleWindows(true

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

window.open(fileUrl);
浏览器中的一切都很好,但在Webview组件中实现这些功能时,新选项卡不会打开

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

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
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"/>


我也尝试使用
setDownloadListener
捕捉下载。另一种方法是将
WebChromeClient()
替换为
WebViewClient()
,但行为是相同的。

好的,我在使用webview时遇到了同样的问题,我意识到WebViewClient不能像Chrome桌面客户端那样加载“blob url”。我用Javascript接口解决了这个问题。您可以通过以下步骤来完成此操作,并且它可以与minSdkVersion:17配合使用。首先,使用JS转换Base64字符串中的Blob URL数据。其次,将这个字符串发送到Java类,最后将其转换为可用格式,在本例中,我将其转换为一个“.pdf”文件

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

第一件事。您必须设置您的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);
    }
}
最后,创建一个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();
    }
}
 
额外:如果要与其他应用共享这些下载的文件,请在以下位置创建一个xml文件:..\res\xml\provider\u paths.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>
科特林:

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


非常感谢您的支持。通知代码错误,但Blob实际上已下载。嘿。这是关于Android Oreo(8.0)在没有事先配置通知通道的情况下没有显示通知。抱歉,如果不清楚:)Blob在我的情况下没有下载。当我在android的webview中单击下载时,什么都没有发生。请提供任何帮助。@Vikrant将其移动到新类可以确认这个答案在2020年仍然有效(虽然我没有直接复制和粘贴它,但采用了它的方法)。如果需要将mime type和download属性从javascript传递到javascript接口(如果需要将其用于多个PDF),例如fileName=document.querySelector('a[href=\''+blobUrl+“\”])。getAttribute('download');
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
    CustomTabsIntent customTabsIntent = builder.build();
    customTabsIntent.launchUrl(context, Uri.parse("https://stackoverflow.com"));
val url = "https://stackoverflow.com/"
            val builder = CustomTabsIntent.Builder()
            val customTabsIntent = builder.build()
            customTabsIntent.launchUrl(this, Uri.parse(url))