hello hello - 9 days ago 7
HTML Question

How to change a form action using Javascript and Selenium in JAVA

I've been trying to replace the action attribute of a form using javascript and selenium in JAVA, but I can't get it to work.

This is the site's snippet HTML:

</div>
<div class="contionue-shopping-wrapper">
<form class="co-formcontinueshopping" action="https://www.yahoo.com" method="post" id="dwfrm_cart_d0jilurhcxpm">
<fieldset>
<button class="rbk-button-red button-primary bp-black right" type="submit" value="Continue Shopping" name="dwfrm_cart_continueShopping">
<span>Continue Shopping</span>
</button>
</fieldset>
</form>
</div>


This is what I've done in JAVA in an attempt to change the action above

String link = "https://www.google.com"
((JavascriptExecutor)atc).executeScript("document.getElementsByClassName('co-formcontinueshopping')[0].action="+link);


(note: atc is the Selenium chrome webdriver and site is loaded at this stage)

EDIT: I think if I convert the following javascript to above it'll work?

document.getElementById(document.querySelector("[id^='dwfrm_cart']").id).action = url})()

Answer

That should actually work, for example this code works:

@Test
public void test() throws InterruptedException{

    driver.get("https://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-Show");
    JavascriptExecutor js=(JavascriptExecutor) driver;

    String link = "'http://www.example.com'"; // notice the extra ' inside the "

    //log the current value of 'action'
    js.executeScript("console.log(document.getElementsByClassName('co-formcontinueshopping')[0].action)");

    //change the value to the value hold by our link
    js.executeScript("document.getElementsByClassName('co-formcontinueshopping')[0].action=" + link);

    //log 'action' again
    js.executeScript("console.log(document.getElementsByClassName('co-formcontinueshopping')[0].action)");

    driver.quit();
}

And the output in the console of the browser is:

https://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-Show/C1360474325
http://www.example.com/

So the approach is right, only in your situation something must be missing such as:

  • the document.getElementsByClassName('co-formcontinueshopping') is returning something wrong, this can have several causes, e.g. the site is in an iframe. Check if the correct element is returned, for example by logging it to the console.
  • the document.getElementsByClassName('co-formcontinueshopping')[0] is returning something else as you expected, check that one too
  • you are setting the action to something else then I did in my example, e.g. I used the ''.
  • something else, such as a different browser (I used Chrome 54.0.2840.98 on Mac)