如何使用JavaScript填写另一页面上的表单

时间:2012-08-29 17:42:14

标签: javascript forms

我正在尝试通过JavaScript填写表单上的字段。问题是我只知道如何在当前页面上执行JavaScript,因此我无法重定向到表单并从那里执行代码。我对使用这个术语犹豫不决,但唯一想到的是跨站脚本。我试图执行的代码如下。

<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>

我不确定这是否可行。我也对其他想法持开放态度,比如PHP。感谢。

编辑:第二页是SharePoint表单。我无法编辑表单上的任何代码。目标是编写一个预填充大部分字段的脚本,因为其中90%是静态的。

4 个答案:

答案 0 :(得分:15)

您正在尝试维护页面之间的状态。通常,有两种方法可以维持状态:

  • 将状态存储在Cookie中
  • 将状态存储在查询字符串

无论哪种方式,您的第一页必须保持状态(对于cookie或查询字符串),而另一页必须 - 单独 - 恢复状态。您不能在两个页面上使用相同的脚本。

示例:使用Cookie

使用cookies,第一页必须将下一页所需的所有表单数据写入cookie:

<!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>

...然后第二页将读取这些cookie并用它们填充表单字段:

<!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>

示例:使用查询字符串

在使用查询字符串的情况下,第一页只会在重定向网址中包含查询字符串,如下所示:

<!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>

...然后表单将解析查询字符串(通过window.location.search在JavaScript中提供 - 前缀为?):

<!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>

示例:使用片段标识符

还有一个选项:由于状态是严格在客户端(而不是服务器端)维护,您可以将信息放在片段标识符(URL的“哈希”部分)中。

第一个脚本与上面的Query String示例非常相似:重定向URL只包含片段标识符。为方便起见,我将重新使用查询字符串格式,但请注意以前#所在地的?

<!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>

...然后表单必须解析片段标识符等:

<!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>

如果您无法编辑表单页面的代码

Try a greasemonkey script.

答案 1 :(得分:1)

这是一个使用cookies

的好地方

例如:来自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;
}

和旁注,您可以使用onload事件来了解页面何时准备就绪

<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>

答案 2 :(得分:1)

如果能够在不访问目标系统/源/ mitm方法的情况下操纵目标网站,那么这将是恶意软件与点击劫持相结合的开放式高速公路!我不希望你的脚本告诉我银行的表格做什么。 ; - )

为此目的使用某种自动化工具,如AutoIt(www.autoitscript.com)。易于学习,并且具有良好的表单集成。如果标准不够,请为AutoIt寻找类似winhttp的UDF。

答案 3 :(得分:0)

使用本地存储非常简单
首页表单

<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>

这是第二页

<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>
相关问题