How to auto-scroll to the end in WebView?


Question

I've problem with Scrollbar in WebView. I want to when the web view loaded, the srollbar auto scroll to the end of web view. How can I do it?

This is my sample

package sample;  
import javafx.fxml.FXML;  
import javafx.fxml.Initializable;  
import javafx.scene.Node;  
import javafx.scene.control.ScrollBar;  
import javafx.scene.web.WebEngine;  
import javafx.scene.web.WebView;  
import java.net.URL;  
import java.util.ResourceBundle;  
import java.util.Set;  
public class Controller implements Initializable {  
    @FXML  
    WebView webView;  
    @Override  
    public void initialize(URL url, ResourceBundle resourceBundle) {  
        loadWebView();  
    }  
    private void loadWebView() {  
        webView.setStyle("-fx-background-color: #cccccc; -fx-border-color: #00a7c8");  
        StringBuilder html= new StringBuilder().append("<html><body>");  
        for (int i=0; i<100; i++) {  
            html.append("<h1>" + i + ". AAAAAAAAAAAA</h1></br>");  
        }  
        html.append("</body></html>");  
        Set<Node> nodes = webView.lookupAll(".scroll-bar");  
        for (Node node : nodes) {  
            if (ScrollBar.class.isInstance(node)) {  
                System.out.println("Scrollbar here!!!");  
                ScrollBar scroll = (ScrollBar) node;  
                scroll.setValue(scroll.getMax());  
            }  
        }  
        WebEngine webEngine = webView.getEngine();  
        webEngine.loadContent(html.toString());  
    }  
}  

Thanks 4 your reading

1
1
10/23/2013 3:04:29 PM

Simply execute this script after your loadContent call:

webEngine.executeScript("window.scrollTo(0, document.body.scrollHeight);");
2
1/18/2017 3:51:33 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon