I am trying to create a browser to get the hands on practice on JavaFX. I implemented the Back button with Stack.
- When the URL of the page change, add url to Stack(java.util.Stack)
- When back button is pressed, pop 1 item from Stack and show the page
But this does not work in case of URL redirection. Eg. I entered http://www.google.com , It automatically redirects to http://www.google.co.in (India). This makes 2 entries in Stack which corrupts the Back button logic since the page is the same but taken from different locations.
Please assist me in fixing this problem.
Thanks for your help
webEngine.locationProperty().addListener(new ChangeListener<String>(){
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
//urlField is a text Field
urlField.setText(newValue);
addURLToStack(oldValue);
if(backButtonStack.size() ==1){ //means on last url of Stack
backButton.setDisable(true);
}
else{
backButton.setDisable(false);
}}
});
backButton.setOnMouseClicked(new EventHandler<MouseEvent>(){
@Override
public void handle(MouseEvent event) {
if(backButtonStack != null && !backButtonStack.isEmpty()){
String poppedURL = backButtonStack.pop();
webEngine.load(poppedURL);
}
}
});
private void addURLToStack(String url) {
if(backButtonStack == null){
backButtonStack = new Stack<String>();
}
backButtonStack.push(url);
}
You don’t need to solve this problem.
JavaFX WebEngine has a WebHistory object which has all the API you need to completely manage the history and it should take care of not adding redirected URLs to the history for you. And, if you don’t want to use that, you can use
webengine.executeScript("history.back()");to have the engine’s JavaScript engine handle the navigation for you.What Chris Gerken says is right about monitoring the http status return codes to work out whether or not to place the object in history. The difficulty with that in the JavaFX
WebEngineis that the http status return codes happen at the network layer and are not exposed through the WebEngine interface. So if you just monitor the location property of the WebEngine as you are doing, it is going to be really hard to get a high quality navigation interface. I found this out when I implemented a JavaFX WebBrowser to get JavaFX experience and my browser’s history mechanism using an ObservableList with a current index pointer had exactly the same issue as you point out in your question. If I were to implement the same functionality again today, I would just make use of the newWebHistoryfunctionality provided by the later JavaFX versions, rather than writing my own.