How can I have many JavaFX WebView
components each with its own private cookie-based session on the same server, e.g. from a UI with many tabs?
As a use case, run the following SSCCE and login to a site (I have been using https://mail.google.com/) from the "Browser 1" tab. Open the same site from the "Browser 2" tab, and you will see the session from "Browser 1". (NOTE: You have to enter the full address, with the protocol prefix - http://
- and press the "Go" button - ENTER will not work.)
EDIT: Using the engine.userDataDirectory
property does not work either.
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.concurrent.Worker.State;
public class TwoBrowserTabs extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
TabPane tabPane = new TabPane();
Tab tab1 = new Tab();
tab1.setText("Browser 1");
tab1.setContent(makeBrowserTab("browser1"));
tabPane.getTabs().add(tab1);
Tab tab2 = new Tab();
tab2.setText("Browser 2");
tab2.setContent(makeBrowserTab("browser2"));
tabPane.getTabs().add(tab2);
Scene scene = new Scene(tabPane);
primaryStage.setTitle("Two browsers");
primaryStage.setScene(scene);
primaryStage.show();
}
private Node makeBrowserTab(String identifier) {
BorderPane borderPane = new BorderPane();
TextField address = new TextField();
HBox.setHgrow(address, Priority.ALWAYS);
Button go = new Button();
go.setText("Go");
HBox hbox = new HBox();
hbox.getChildren().add(address);
hbox.getChildren().add(go);
WebView browser = new WebView();
browser.setPrefSize(960, 640);
borderPane.setTop(hbox);
borderPane.setCenter(browser);
WebEngine engine = browser.getEngine();
// EDIT: Does not work either
engine.setUserDataDirectory(new File(System.getProperty("user.home") + File.separator + "TwoBrowserTabs" + File.separator + identifier));
// Let the button reflect the state of the loader,
// so as to have a minimalistic feedback.
engine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
if( newState == State.READY || newState == State.SUCCEEDED ) {
go.setDisable(false);
go.setText("Go");
}
else if( newState == State.FAILED || newState == State.CANCELLED ) {
go.setDisable(false);
go.setText("Go (!)");
}
else {
go.setDisable(true);
go.setText("Go");
}
});
go.setOnAction(event -> {
engine.load(address.getText());
});
return borderPane;
}
public static void main(String[] args) {
launch(args);
}
}