hello hello - 1 month ago 18
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 class="contionue-shopping-wrapper">
<form class="co-formcontinueshopping" action="https://www.yahoo.com" method="post" id="dwfrm_cart_d0jilurhcxpm">
<button class="rbk-button-red button-primary bp-black right" type="submit" value="Continue Shopping" name="dwfrm_cart_continueShopping">
<span>Continue Shopping</span>

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

String link = "https://www.google.com"

(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})()


That should actually work, for example this code works:

public void test() throws InterruptedException{

    JavascriptExecutor js=(JavascriptExecutor) driver;

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

    //log the current value of 'action'

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

    //log 'action' again


And the output in the console of the browser is:


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)