forked from react-native-webview/react-native-webview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlobFileDownloader.kt
More file actions
84 lines (73 loc) · 2.98 KB
/
BlobFileDownloader.kt
File metadata and controls
84 lines (73 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.reactnativecommunity.webview.extension.file
import android.webkit.JavascriptInterface
import com.reactnativecommunity.webview.RNCWebView
import com.reactnativecommunity.webview.extension.file.Base64FileDownloader.downloadBase64File
import java.io.IOException
internal fun RNCWebView.addBlobFileDownloaderJavascriptInterface(downloadingMessage: String, requestFilePermission: (String) -> Unit) {
this.addJavascriptInterface(
BlobFileDownloader(this, downloadingMessage, requestFilePermission),
BlobFileDownloader.JS_INTERFACE_TAG,
)
}
internal class BlobFileDownloader(
private val webView: RNCWebView,
private val downloadingMessage: String,
private val requestFilePermission: (String) -> Unit,
) {
@JavascriptInterface
@Throws(IOException::class)
fun getBase64FromBlobData(base64: String) {
if (!webView.allowFileDownloads) {
return
}
downloadBase64File(webView.context, base64, downloadingMessage, requestFilePermission)
}
companion object {
const val JS_INTERFACE_TAG: String = "BlobFileDownloader"
/**
* Invokes JS method downloadBlob from [getBlobFileInterceptor]
*/
fun getDownloadBlobInterceptor(url: String): String = "downloadBlob('$url');"
/**
* This script handles Blob downloading in two ways:
* 1) It intercepts clicks on elements with a Blob: href.
* 2) It defines a method, downloadBlob, which is manually invoked from Android [com.reactnativecommunity.webview.RNCWebViewManagerImpl] in cases where the href is undefined.
*/
fun getBlobFileInterceptor(): String = """
(function() {
if (window.blobDownloadInjected) return;
window.blobDownloadInjected = true;
function blobToBase64(blob, callback) {
const reader = new FileReader();
reader.onloadend = function() {
const base64 = reader.result;
callback(base64);
};
reader.readAsDataURL(blob);
}
function downloadBlobUrl(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (this.status === 200) {
const blob = this.response;
blobToBase64(blob, function(base64) {
${JS_INTERFACE_TAG}.getBase64FromBlobData(base64);
});
}
};
xhr.send();
}
document.addEventListener('click', function(e) {
const target = e.target;
if (target.tagName === 'A' && target.href && target.href.startsWith('blob:')) {
e.preventDefault();
downloadBlobUrl(target.href);
}
}, true);
window.downloadBlob = downloadBlobUrl;
})();
""".trimIndent()
}
}