Search code examples
javascriptjavaseleniumautomated-testsbrowser-automation

Javascript error: missing ) after argument list


I fail to find the cause for this error. It seems to be on the 4th line. I have tried various different ways. Could anyone point out where I am going wrong with this pls?

public WebElement jsQuery(String componentQuery) {
    String cmd = "arguments[0].querySelector('" + componentQuery +"')";
    String js = "return " + cmd + ".id;";
   // String id = (String) js.executeScript("return document.querySelector('" + componentQuery +"').id");
    String id = (String) ((JavascriptExecutor) driver).executeScript(js);
    waitForJavascript(5000, 3);
    return driver.findElement(By.id(id));
}

Solution

  • You need to escape quotes in the componentQuery Java variable.

    String componentQueryEscaped = componentQuery.replaceAll("'", "\'");
    

    you can also change your JS code to use the backtick instead of single quote:

    "arguments[0].querySelector(`" + componentQuery + "`)";
    

    But the first solution is more solid.