user5681278
user5681278

Reputation:

Selenium/WebView get clicked element

Is it possible to open a browser using the WebDriver class in Selenium and get the elements that the user is clicking?

I already looked through the documentation of selenium and found nothing useful.

I already thought about inserting a javascript function into the webpage, that gets called whenever a clickable element is clicked, but I dont know how I would then retrieve that information into my java programm. Any ideas on how to solve this problem?

Upvotes: 2

Views: 1984

Answers (1)

user5681278
user5681278

Reputation:

Managed to solve this problem with the hint that Saurabh Gaur gave me

Here is my HTML document that I tested the application with, its called Index.html:

<html>
<head>
    <title>I am the title, haha!</title>
</head>
<body>
    <p id="id1">I am id1</p>
    <a href="www.google.com" id="ihatejava">end my suffering</a>
<body>
</html>

and here is my java code. all it does is add a listener to the HTML elements:

public class Main extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage stage) throws MalformedURLException {
    WebView webView = new WebView();
    WebEngine engine = webView.getEngine();
    engine.load(new File("PATH/TO/Index.html").toURI().toURL().toExternalForm());

    Scene scene = new Scene(webView);
    stage.setScene(scene);
    stage.show();

    //we need this to check if the document has finished loading, otherwise it would be null and throw a exception
    engine.getLoadWorker().stateProperty().addListener((obs, oldState, currentState) -> {
        if (currentState == State.SUCCEEDED) {
            Document doc = engine.getDocument();
            addListeners(doc);
        }
    });
}

private void addListeners(Document doc) {
    Element link1 = doc.getElementById("id1");
    ((EventTarget) link1).addEventListener("click", e -> {
        System.out.println("id1 was clicked!");
    }, false);

    Element link2 = doc.getElementById("ihatejava");
    ((EventTarget) link2).addEventListener("click", e -> {
        System.out.println("ihatejava was clicked!");
    }, false);
}
}

Upvotes: 5

Related Questions