Does WebView saveState() preserve Javascript variables/environment?

后端 未结 2 477
不知归路
不知归路 2020-12-29 15:49

I\'ve searched many threads and still cannot find the answer to my question. I\'m working on an Android app which uses WebView.

I use

相关标签:
2条回答
  • 2020-12-29 16:41

    As user2113581 commented, moving the WebView into a context of the application rather than the Activity is a potential solution. This still has all of the pitfalls that user2113581 mentioned, including <select> not working (because it creates a window, but an application context does not have a window token).

    I have extended my Application to manage my webview...

    MyApplication.java:

    public class MyApplication extends Application {
      private WebView mWebView;
      private boolean mWebViewInitialized;
      // ...
    
      @Override public void onCreate() {
        super.onCreate();
        mWebView = new WebView(this);
        mWebViewInitialized = false; // we do some initialization once in our activity.
      }
    
      public WebView getWebView() { return mWebView; }
      public boolean isWebViewInitialized() { return mWebViewInitialized; }
      public void setWebViewInitialized(boolean initialized) {
        mWebViewInitialized = initialized;
      }
    }
    

    In our activity:

    @Override protected void onCreate(Bundle savedInstanceState) {
      // ...
      MyApplication app = (MyApplication) getApplication();
      mWebView = app.getWebView();
      if (!app.isWebViewInitialized()) { 
        /* first time initialization */ 
        app.setWebViewInitialized(true);
      }
    }
    

    Finally, in your Activity, you will want to add the mWebView to a container view (FrameLayout, or similar) during a lifecycle event that makes sense. You'll need to remove it from the container when the activity is being paused or stopped. I've used onResume and onPause with good results.

    0 讨论(0)
  • 2020-12-29 16:47

    Very few information found, only this line:

    Please note that this method no longer stores the display data for this WebView. The previous behavior could potentially leak files if restoreState(Bundle) was never called.

    and this line:

    Returns the same copy of the back/forward list used to save the state.

    in the javadoc for WebView.saveState(Bundle).

    0 讨论(0)
提交回复
热议问题