How to program Back and Forward buttons in JavaFX with WebView and WebEngine?


Question

I'm learning JavaFX, trying to write a simple browser, but how do I program the Back and Forward buttons in JavaFX with WebView and WebEngine ? Any sample code ?

1
4
9/21/2013 2:36:42 AM

Accepted Answer

I figured it out :

  public String goBack()
  {    
    final WebHistory history=eng.getHistory();
    ObservableList<WebHistory.Entry> entryList=history.getEntries();
    int currentIndex=history.getCurrentIndex();
//    Out("currentIndex = "+currentIndex);
//    Out(entryList.toString().replace("],","]\n"));

    Platform.runLater(new Runnable() { public void run() { history.go(-1); } });
    return entryList.get(currentIndex>0?currentIndex-1:currentIndex).getUrl();
  }

  public String goForward()
  {    
    final WebHistory history=eng.getHistory();
    ObservableList<WebHistory.Entry> entryList=history.getEntries();
    int currentIndex=history.getCurrentIndex();
//    Out("currentIndex = "+currentIndex);
//    Out(entryList.toString().replace("],","]\n"));

    Platform.runLater(new Runnable() { public void run() { history.go(1); } });
    return entryList.get(currentIndex<entryList.size()-1?currentIndex+1:currentIndex).getUrl();
  }
7
9/24/2013 6:19:28 PM

if you don't need to get or set any indices, here is a concise way with javascript to code the back and forward buttons for a custom contextMenu:

public void goBack() {
    Platform.runLater(() -> {
        webEngine.executeScript("history.back()");
    });
}

public void goForward() {
    Platform.runLater(() -> {
        webEngine.executeScript("history.forward()");
    });
}

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