10

I am trying to fill out the fields on a form through JavaScript. The problem is I only know how to execute JavaScript on the current page so I cannot redirect to the form and execute code from there. I'm hesitant to use this term, but the only phrase that comes to mind is cross-site script. The code I am attempting to execute is below.

<script language="javascript"> 

window.location = "http://www.pagewithaform.com";

loaded();

//checks to see if page is loaded. if not, checks after timeout.
function loaded()
{
    if(window.onLoad)
    {
      //never executes on new page. the problem
      setTitle();
    }
    else
    {
      setTimeout("loaded()",1000);
      alert("new alert");
    }
}

//sets field's value
function setTitle()
{
    var title = prompt("Field Info","Default Value");
    var form = document.form[0];
    form.elements["fieldName"].value = title;
}
</script>

I'm not truly sure if this is possible. I'm also open to other ideas, such as PHP. Thanks.

EDIT: The second page is a SharePoint form. I cannot edit any of the code on the form. The goal is to write a script that pre-fills most of the fields because 90% of them are static.

spassen
  • 1,550
  • 8
  • 20
  • 32
  • why don't you use cookies or localStorage, or store the values in flash scope/session and them for next page – Ankur Aug 29 '12 at 17:44
  • I don't have any access to the next page. It's a form on SharePoint that I'm tired of filling out repeatedly. Most of the fields are going to be the same every time so I was hoping to fill those in with the script. Is there a way to do anything you mentioned for that? – spassen Aug 29 '12 at 17:53
  • you can't do that until you have some sort of API available from sharepoint, because if it was it will cause serious security issues – Ankur Aug 29 '12 at 17:54
  • If you want you can setup a proxy server in apache and then you can have access to the webpage from sharepoint. – Ankur Aug 29 '12 at 17:56
  • Why not just create an Extension plugin like for chrome, then you could auto-fill the loaded webpages HTML form easy. – John G Martin Apr 04 '19 at 04:32

4 Answers4

17

You're trying to maintain state between pages. Conventionally there are two ways to maintain state:

  • Store state in cookies
  • Store state in the query string

Either way your first page has to persist state (to either cookies or the query string) and the other page has to - separately - restore the state. You can't use the same script across both pages.

Example: Using Cookies

Using cookies, the first page would have to write all the form data you'll need on the next page to cookies:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With Cookies</title>
 </head>
 <body>
     <div>
         Setting cookies and redirecting...
     </div>
     <script>
         // document.cookie is not a real string
         document.cookie = 'form/title=My Name is Richard; expires=Tue, 29 Aug 2017 12:00:01 UTC'
         document.cookie = 'form/text=I am demoing how to use cookies in JavaScript; expires=Tue, 29 Aug 2017 12:00:01 UT';
         setTimeout(function(){
             window.location = "./form-cookies.html";
         }, 1000);
     </script>
 </body>
</html>

... and the second page would then read those cookies and populate the form fields with them:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With Cookies</title>
 </head>
 <body>
     <form id="myForm" action="submit.mumps.cgi" method="POST">
         <input type="text" name="title" />
         <textarea name="text"></textarea>
     </form>
     <script>
         var COOKIES = {};
         var cookieStr = document.cookie;
         cookieStr.split(/; /).forEach(function(keyValuePair) { // not necessarily the best way to parse cookies
             var cookieName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
             var cookieValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
             COOKIES[cookieName] = cookieValue;
         });
         document.getElementById("myForm").getElementsByTagName("input")[0].value = COOKIES["form/title"];
         document.getElementById("myForm").getElementsByTagName("textarea")[0].value = COOKIES["form/text"];
     </script>
 </body>
</html>

Example: Using the Query String

In the case of using the Query String, the first page would just include the query string in the redirect URL, like so:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Query String</title>
 </head>
 <body>
     <div>
         Redirecting...
     </div>
     <script>
         setTimeout(function(){
             window.location = "./form-querystring.html?form/title=My Name is Richard&form/text=I am demoing how to use the query string in JavaScript";
         }, 1000);
     </script>
 </body>
</html>

...while the form would then parse the query string (available in JavaScript via window.location.search - prepended with a ?):

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Query String</title>
 </head>
 <body>
     <form id="myForm" action="submit.mumps.cgi" method="POST">
         <input type="text" name="title" />
         <textarea name="text"></textarea>
     </form>
     <script>
         var GET = {};
         var queryString = window.location.search.replace(/^\?/, '');
         queryString.split(/\&/).forEach(function(keyValuePair) {
             var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
             var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
             GET[paramName] = paramValue;
         });
         document.getElementById("myForm").getElementsByTagName("input")[0].value = GET["form/title"];
         document.getElementById("myForm").getElementsByTagName("textarea")[0].value = GET["form/text"];
     </script>
 </body>
</html>

Example: With a Fragment Identifier

There's one more option: since state is being maintained strictly on the client side (not on th server side) you could put the information in a fragment identifier (the "hash" part of a URL).

The first script is very similar to the Query String example above: the redirect URL just includes the fragment identifier. I'm going to re-use query string formatting for convenience, but notice the # in the place where a ? used to be:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Fragment Identifier</title>
 </head>
 <body>
     <div>
         Redirecting...
     </div>
     <script>
         setTimeout(function(){
             window.location = "./form-fragmentidentifier.html#form/title=My Name is Richard&form/text=I am demoing how to use the fragment identifier in JavaScript";
         }, 1000);
     </script>
 </body>
</html>

... and then the form has to parse the fragment identifier etc:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Fragment Identifier</title>
 </head>
 <body>
     <form id="myForm" action="submit.mumps.cgi" method="POST">
         <input type="text" name="title" />
         <textarea name="text"></textarea>
     </form>
     <script>
         var HASH = {};
         var hashString = window.location.hash.replace(/^#/, '');
         hashString.split(/\&/).forEach(function(keyValuePair) {
             var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
             var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
             HASH[paramName] = paramValue;
         });
         document.getElementById("myForm").getElementsByTagName("input")[0].value = HASH["form/title"];
         document.getElementById("myForm").getElementsByTagName("textarea")[0].value = HASH["form/text"];
     </script>
 </body>
</html>

And if you can't edit the code for the form page

Try a greasemonkey script.

Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
1

It is a good place to use cookies

Ex: From quirksmode.org

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

and a side note, you can use the onload event to know when the page is ready

<script language="javascript"> 

function setTitle(){
    var title = prompt("Field Info","Default Value");
    var form = document.form[0];
    form.elements["fieldName"].value = title;
}

windows.onload = setTitle;

</script>
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • I may be wrong, but I don't think I can use cookies in my case. For them to work, wouldn't I need to access them through code in the next page? I don't have access to the source for the second page. It's a SharePoint form that I am tired of filling out every time. 90% of the fields' values are static. I was hoping to just set the values with the script and prompt for the title so I could just click OK on the next page. – spassen Aug 29 '12 at 17:58
  • @spassen if your form is in your own server, you can do what ever you want. the form can be populated using javascript – Ibu Aug 29 '12 at 18:00
1

If it would be possible to manipulate target websites without access to the target's system/source/mitm-methods then this would really be an open highway for malware in combination with clickjacking! I do not want your script to tell the form of my bank what to do. ;-)

Use some kind of automation tools like AutoIt (www.autoitscript.com) for this purpose. Easy to learn and it hast good Form integration. If standard is not enough, look for UDFs like winhttp for AutoIt.

Zec
  • 19
  • 6
1

Its very easy using local storage
The first page form

<style>
  input{
    font-size: 25px;
  }
  label{
    color: rgb(16, 8, 46);
    font-weight: bolder;
  }
  #data{

  }
</style>
<script>
function getData()
{
    //gettting the values
    var email = document.getElementById("email").value;
    var password= document.getElementById("password").value; 
    var telephone= document.getElementById("telephone").value; 
    var mobile= document.getElementById("mobile").value; 
    //saving the values in local storage
    localStorage.setItem("txtValue", email);
    localStorage.setItem("txtValue1", password);
    localStorage.setItem("txtValue2", mobile);
    localStorage.setItem("txtValue3", telephone);   
}
</script>

   <fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
        <form action="action.html">
        <legend>Sign Up Form</legend>
        <label>Email:<br />
        <input type="text" name="email" id="email"/></label><br />
        <label>Password<br />
        <input type="text" name="password" id="password"/></label><br>
        <label>Mobile:<br />
        <input type="text" name="mobile" id="mobile"/></label><br />
        <label>Telephone:<br />
        <input type="text" name="telephone" id="telephone"/></label><br> 
        <input type="submit" value="Submit" onclick="getData()">
    </form>
    </fieldset>

This is the second Page

<script>
//displaying the value from local storage to another page by their respective Ids
document.getElementById("data").innerHTML=localStorage.getItem("txtValue");
document.getElementById("data1").innerHTML=localStorage.getItem("txtValue1");
document.getElementById("data2").innerHTML=localStorage.getItem("txtValue2");
document.getElementById("data3").innerHTML=localStorage.getItem("txtValue3");
</script>
 <div style=" font-size: 30px;  color: rgb(32, 7, 63); text-align: center;">
    <div style="font-size: 40px; color: red; margin: 0 auto;">
        Here's Your data
    </div>
    The Email is equal to: <span id="data"> Email</span><br> 
    The Password is equal to <span id="data1"> Password</span><br>
    The Mobile is equal to <span id="data2"> Mobile</span><br>
    The Telephone is equal to <span id="data3"> Telephone</span><br>
    </div>
bilalmohib
  • 280
  • 3
  • 16