Reputation: 497
Can I save the DOM of an Andoird WebView to a file in the local storage? On the other hand, in a different App, is it possible to load a WebView from the DOM file stored in the local storage?
I am asking this because I need to save the online form data in a webpage and make sure I can load the exactly same webpage (including the form data) in a different App.
I am a newbie of android and JavaScript. I read some post about manipulating the DOM in JavaScript, but I have no idea about how to do that with Android WebView. Could anyone show me some sample code of saving the DOM of a WebView to shared storage using JavaScript, and the code of loading a webpage from the DOM files.
Thanks a lot!
Upvotes: 3
Views: 2320
Reputation: 1759
As I have mentioned in comments, it is not possible to access contents of local storage from another application. Instead you can save the contents to a file and use that in the other application.
Get DOM:
from webview,
var dom = document.getElementsByTagName('html')[0].outerHTML;
Store it to file using Javascript Interface
From documentation;
Injects the supplied Java object into this WebView. The object is injected into the JavaScript context of the main frame, using the supplied name. This allows the Java object's methods to be accessed from JavaScript. For applications targeted to API level JELLY_BEAN_MR1 and above, only public methods that are annotated with JavascriptInterface can be accessed from JavaScript.
Class FileWriter{
@JavascriptInterface
public void writeToFile(String dataToBeWritten) {
writeDataToFile(dataToBeWritten);
}
public static void writeDataToFile(Sting data){
// java code to write data to file
}
}
In your main activity,
webView.addJavascriptInterface(new FileWriter(), "FileWriter");
This exposes FileWriter as an object in global namespace in JavaScript land of webview.
Now from JavaScript:
FileWriter.writeToFile(dom);
Will create a file in the specified location with passed data.
Hope this helps.
Upvotes: 4