0

I am a novice in selenium. I want to hit a url, search for all the iframes and in every iframe, I want to inject a Javascript code. So how would I do that. So far, I have come up with basic selenium code but do not know how to inject JS.

public class Poc {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver","/home/xxx/xxx/xxx/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("http://www.sss.org/");

        List<WebElement> elements = driver.findElements(By.tagName("iframe"));
        for(WebElement element:elements) {
            System.out.println(element.getAttribute("id"));
        }
        driver.close();
        System.exit(0);

    }
}
1
  • 1
    What is the actual url ? Is it sss.org ? Btw, why do you want to inject JS into the page ? Maybe there is an alternate solution for your needs. Commented Sep 28, 2016 at 16:43

2 Answers 2

3

To inject code into each iframe you first have to switch to it

import org.openqa.selenium.JavascriptExecutor;

List<WebElement> elements = driver.findElements(By.tagName("iframe"));
for(WebElement element:elements) {
    driver.switchTo().defaultContent();
    driver.switchTo.frame(element);
    if (driver instanceof JavascriptExecutor) {
        ((JavascriptExecutor) driver).executeScript("alert('hello world');");
    }
    System.out.println(element.getAttribute("id"));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use JavascriptExecutor for writing javascript code in selenium

Example code for you is

JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
js.executeScript("arguments[0].setAttribute('attr', '10')",element);

1 Comment

Can you please explain whats happening in the 3rd line. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.