Skip to content Skip to sidebar Skip to footer

Java - How Can You Call A Variable Inside A String Using Javascriptexecutor?

Im using selenium webdriver(JAVA) on testing and I have a fire event method that should be reusable depending on the locator that is passed into it. My code is below : public void

Solution 1:

You might have a go

publicvoidfireEvent(String elementId) {
     ((JavascriptExecutor) driver).executeScript("return document.getElementById('arguments[0]').blur()", elementId);
}

Instead of passing string elementId in, you might also try pass the element itself in, so that you don't need to worry about ById or ByClassName anymore.

publicvoidfireEvent(WebElement element) {
     ((JavascriptExecutor) driver).executeScript("return arguments[0].blur()", element);
}

Solution 2:

The javascript code that receives "executeScript" is a regular String, you can compose this String as usual, for example:

publicvoidfireEvent(String locator) {
  String jsToExecute = String.format("return document.getElementById('%s').blur()", locator​​​​​​​​​​​​​​​)​
  ((JavascriptExecutor) driver).executeScript(jsToExecute);
}

Post a Comment for "Java - How Can You Call A Variable Inside A String Using Javascriptexecutor?"