Extracting text from an element
private String jsGetElementText(String cssSelector) {
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
return (String) javascriptExecutor.executeScript(String.format(
"var element = document.querySelector(\"%s\");\n" +
"if(element != null){\n" +
" return element.innerHTML;\n" +
"}else{\n" +
" return \"\";\n" +
"}", cssSelector));
}
Performing Drag and Drop with a file
public void dropFile(File filePath, WebElement target, int offsetX, int offsetY) {
if (!filePath.exists())
throw new WebDriverException("File not found: " + filePath.toString());
JavascriptExecutor jse = (JavascriptExecutor) driver;
String JS_DROP_FILE =
"var target = arguments[0]," +
" offsetX = arguments[1]," +
" offsetY = arguments[2]," +
" document = target.ownerDocument || document," +
" window = document.defaultView || window;" +
"" +
"var input = document.createElement('INPUT');" +
"input.type = 'file';" +
"input.style.display = 'none';" +
"input.onchange = function () {" +
" var rect = target.getBoundingClientRect()," +
" x = rect.left + (offsetX || (rect.width >> 1))," +
" y = rect.top + (offsetY || (rect.height >> 1))," +
" dataTransfer = { files: this.files };" +
"" +
" ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
" var evt = document.createEvent('MouseEvent');" +
" evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
" evt.dataTransfer = dataTransfer;" +
" target.dispatchEvent(evt);" +
" });" +
"" +
" setTimeout(function () { document.body.removeChild(input); }, 25);" +
"};" +
"document.body.appendChild(input);" +
"return input;";
WebElement input = (WebElement) jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
input.sendKeys(filePath.getAbsoluteFile().toString());
waitFor(ExpectedConditions.stalenessOf(input));
}
Adjusting opacity for a field
public void changeOpacityForUploadField() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.querySelector(\"input[id*='upload']\").style.opacity='1'");
}
Halting page loading process
public void stopPageLoading() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return window.stop");
}
Triggering browser extension to open
public void openBrowserExtension(){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.postMessage('clicked_browser_action', '*')");
}
Waiting for the page to finish loading
public void waitForPageLoad(){
JavascriptExecutor js = (JavascriptExecutor) driver;
waitForCondition().until(d->js.executeScript("return document.readyState").equals("complete"));
}