เราสามารถอ่านตัวแปร Javascript ด้วย Selenium webdriver ซีลีเนียมสามารถเรียกใช้คำสั่ง Javascript ด้วยความช่วยเหลือของ executeScript กระบวนการ. คำสั่ง Javascript ที่จะดำเนินการจะถูกส่งผ่านเป็นอาร์กิวเมนต์ของเมธอด นอกจากนี้ เราต้องเพิ่มคำสั่ง import org.openqa.selenium.JavascriptExecutor เพื่อทำงานกับ Javascript
ไวยากรณ์
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("return document.title") ให้เราได้รับชื่อเบราว์เซอร์ของหน้าด้านล่างโดยการอ่านค่าจากตัวแปร Javascript ผลลัพธ์ควรเป็น เกี่ยวกับอาชีพที่ Tutorials Point – Tutorialspoint

ตัวอย่าง
การติดตั้งโค้ด
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class JavascriptReadValue{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// Javascript executor to read value
JavascriptExecutor j = (JavascriptExecutor) driver;
// get the browser title with document.title
String t = (String)j.executeScript("return document.title");
System.out.print("Current page title: " +t);
driver.close();
}
} ผลลัพธ์
