简体   繁体   English

如何将Android Web视图保存到DOM,并从给定DOM加载Web视图?

[英]How to save an Android webview to DOM, and load a webview from a given DOM?

Can I save the DOM of an Andoird WebView to a file in the local storage? 我可以将Andoird WebView的DOM保存到本地存储中的文件吗? On the other hand, in a different App, is it possible to load a WebView from the DOM file stored in the local storage? 另一方面,在其他应用程序中,是否可以从本地存储中存储的DOM文件加载WebView?

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. 我是android和JavaScript的新手。 I read some post about manipulating the DOM in JavaScript, but I have no idea about how to do that with Android WebView. 我读了一些有关在JavaScript中操作DOM的文章,但我不知道如何使用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. 谁能给我展示一些使用JavaScript将WebView的DOM保存到共享存储中的示例代码,以及从DOM文件加载网页的代码。

Thanks a lot! 非常感谢!

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: 获取DOM:

from webview, 从网络视图

var dom = document.getElementsByTagName('html')[0].outerHTML;

Store it to file using Javascript Interface 使用Javascript界面​​将其存储到文件中

From documentation ; 文件 ;

Injects the supplied Java object into this WebView. 将提供的Java对象注入此WebView中。 The object is injected into the JavaScript context of the main frame, using the supplied name. 使用提供的名称将对象注入到主框架的JavaScript上下文中。 This allows the Java object's methods to be accessed from JavaScript. 这允许从JavaScript访问Java对象的方法。 For applications targeted to API level JELLY_BEAN_MR1 and above, only public methods that are annotated with JavascriptInterface can be accessed from JavaScript. 对于以API级别JELLY_BEAN_MR1及更高版本为目标的应用程序,只能从JavaScript访问用JavascriptInterface注释的公共方法。

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. 这会将FileWriter公开为webview的JavaScript领域的全局命名空间中的对象。

Now from JavaScript: 现在从JavaScript:

FileWriter.writeToFile(dom);

Will create a file in the specified location with passed data. 将在指定位置创建一个包含传递数据的文件。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM