1

I am trying to execute a javascript method on a webpage with the selenium WebDriver. I am able to execute my own script on the page, but not call the method from the page's HTML. Here is the HTML

 function Search(){ if(check(document.forms[0],"searchResults")){ var fieldCode = ""; var fieldText = ""; if((document.forms[0].elements['prrSearchVO.selectedSearchCriteria.prrNumber'].value =="") && (!isPRRNoSelected())) { alert('PRR No. must be a selected field.'); unSelectAllOptions(document.forms[0].availableFieldsListArray); unSelectAllOptions(document.forms[0].selectedFieldsList); } else { document.forms[0].excelRequested.value = "false"; document.forms[0].action = "prrSearchResults.do"; document.forms[0].submit(); } } } 

If i attempt to submit the form manually it does not load properly. I can execute my own javascript using the code below. How can I execute the "Search" function from the page?

JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.getElementById('fromIssueDate').removeAttribute('readOnly')"); 

    1 Answer 1

    2

    First of all you shouldn't execute javascript using WebDriver unless you really have no other option. Why doesn't the submit work? what did you try? In my experience sometimes click doesn't trigger form submission, so instead you use submit on the form element. Note that if you submit on a non-form element its a no-op. So something like below should work,

     WebElement email = driver.findElement(By.id("email")); WebElement password = driver.findElement(By.id("password")); WebElement submit = driver.findElement(By.id("submit")); email.sendKeys("John"); email.password("foo"); submit.submit(); 

    Going back to your original question, is Search() a global function? Then you could do something like below, however like I said, WebDriver doesn't recommend you invoke javascript since that's not how real users would interact with your application

    JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.Search();"); 
    1
    • I tried setting the values of the form via javascript and then submitting the form, but the page returns an error. The purpose is automating report downloading, not testing. Working now, thanks!
      – Kurter21
      CommentedJun 19, 2015 at 1:12

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.