0

I have tried Download Blob file from Website inside Android WebViewClient and similar others. But not worked. Getting error in console like "Not allowed to load local resource: blob:https:"

fun getBase64FromBlobUrl(blobUrl:String):String{
    if(blobUrl.startsWith("blob")){
        return "javascript: var xhr = new XMLHttpRequest();" +
                "xhr.open('GET', '"+ blobUrl +"', true);" +
                "xhr.setRequestHeader('Content-type','image/png;charset=UTF-8');" +
                "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;" +
                "            androidBridge.getBase64FromBlobData(base64data);" +
                "        }" +
                "    }" +
                "};" +
                "xhr.send();"
    }
    return "javascript: console.log('It is not a Blob URL');";
}

fun provideImageFile(fileName: String,context: Context): File =
    File("${getCacheDir(context)}${fileName}.png")
private fun getCacheDir(context:Context): String {
    val dir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) ?: context.filesDir
    return dir.absolutePath + File.separator
}

class AndroidJsInterface(val context: Context){
    @JavascriptInterface
    fun getBase64FromBlobData(base64Data:String){
        convertBase64StringToImageAndStoreIt(base64Image = base64Data)
    }

    private fun convertBase64StringToImageAndStoreIt(base64Image:String){
        val file = provideImageFile("example", context = context)
        val imageAsBytes = Base64.decode(base64Image.replaceFirst("^data:image/png;base64,", ""), 0)
        val fileOutputStream = FileOutputStream(file,false)
        try {
            fileOutputStream.write(imageAsBytes)
        }
        catch (e:Exception){
            e.printStackTrace()
        }finally {
            fileOutputStream.flush()
        }

    }
}

private fun WebView.configureWebView() {
    settings.javaScriptEnabled = true
    settings.domStorageEnabled = true
    settings.allowFileAccess = true
    settings.databaseEnabled = true
    settings.defaultTextEncodingName = "UTF-8"
    settings.javaScriptCanOpenWindowsAutomatically = true
    settings.allowUniversalAccessFromFileURLs = true
    addJavascriptInterface(AndroidJsInterface(context),JS_OBJECT_NAME)

}

call like 
webview.evaluateJavascript(getBase64FromBlobUrl(blobUrl = url),null)
CodeWithVikas
  • 1,105
  • 9
  • 33

0 Answers0