I have a Blob object inside my WebView, how can I pass it to Android?
I want to save it to local file on device.
I been trying to use:
var url = webkitURL.createObjectURL(myBlob);
But I wasn't been able to download it to device.
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. Finally, create a JavaScriptInterface class.
The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format.
An SQL BLOB is a built-in type that stores a Binary Large Object as a column value in a row of a database table. By default drivers implement Blob using an SQL locator(BLOB) , which means that a Blob object contains a logical pointer to the SQL BLOB data rather than the data itself.
A Blob is an opaque reference to, or handle for, a chunk of data. The name comes from SQL databases, where it means “Binary Large Object.” In JavaScript, Blobs often represent binary data, and they can be large, but neither is required: a Blob could also represent the contents of a small text file.
I haven't tried this, but i was able to found some information pointing to the usage of Javascript Interfaces with WebViews. Basically you can assign Java Classes to work like Javascript classes in your WebView (and exchange information between both sides). I'm not a pro at JavaScript object types, so i'll leave that to you.
First, create a JavaScriptHandler
class with a reference to your activity that controls the WebView
:
public class JavaScriptHandler {
MyActivity parentActivity;
public JavaScriptHandler(MyActivity activity) {
parentActivity = activity;
}
public void doSomething(<Your blob format> data){
// .............
// ..Some code..
// .............
}
}
After that you'll be adding your JavaScriptHandler
to your WebView
in your main Activity
. Don't forget to enable JavaScript in your WebView
!
myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new JavaScriptHandler(this), "MyHandler");
The first parameter passed to addJavaScriptInterface() is the JavaScript interface object itself. The second parameter is the name of the global JavaScript variable which the JavaScript interface object is bound to.
Now all you gotta do is call your Java
method with JavaScript
.
<html>
<head>
<script type="text/javascript">
function sendBlob() {
MyHandler.doSomething(<Your Blob>);
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="sendBlob()" />
</form>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With