To put it simple: I want to bookmark the current position (probably several positions) in a html file displayed in a WebView to later restore it. Any little hint would help. :)
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken web view to show html content.
webView. setWebViewClient(new WebViewClient(){ public void onPageStarted(WebView view, String url, Bitmap favicon) { super. onPageStarted(view, url, favicon); } public boolean shouldOverrideUrlLoading(WebView view, String url) { webView. postUrl(Base_Url, postData.
WebViews automatically persist cookies into a android. webkit. CookieManager. Need to store cookies from a WebView into a java.
The loadUrl() and loadData() methods of Android WebView class are used to load and display web page.
If by "the current position" you mean a point somewhere in a given page, I do not believe that is possible...at least not purely from Java. The whole WebKit API exposed to Java lacks much of anything that deals with the content of pages.
If you have control over the page content, and there's a way to know these positions via in-page Javascript, you could:
Step #1: Use WebView#addJavascriptInterface()
to add an object with some sort of recordPosition()
method, saving the information wherever is appropriate
Step #2: Create a Javascript function that calls recordPosition()
on the injected object.
and then either:
Step #3a: Trigger that Javascript function from Javascript itself (e.g., based on a click), or
Step #3b: Call loadUrl("javascript:...");
on your WebView
, where ...
is replaced by Javascript code to trigger the Javascript function from step #2.
Restoring these positions would have to work much the same way: have Javascript do the actual restores, possibly triggered by Java code.
Note that I have no idea if what you want (get/set the current position) is available from Javascript, as I'm not much of an in-browser coder.
The approach I took was as follows:
In the onSaveInstanceState()
method, calculate how far down the page the user had scrolled.
int contentHeight = webView.getContentHeight();
int scrollY = webView.getScrollY();
float scrollPercent = ((float) scrollY / ((float) contentHeight));
Stash that in the bundle. When restoring the page in the onCreate()
method, wait for the page to finish loading (in WebClient.onPageFinished()
), scroll to the recorded position:
int contentHeight = webView.getContentHeight();
int y = (int) ((float) contentHeight * scrollPercent);
webView.scrollTo(0, y);
float
and calculating a ratio works in the case of flipping between landscape and portrait.onPause()
method, and then webView.setInitialScale(scale)
before you start loading the page.scrollPercent > 0
looks better.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