【问题标题】:How to use JavaScript to fill a form on another page如何使用 JavaScript 在另一个页面上填写表单
【发布时间】:2012-08-24 09:30:25
【问题描述】:

我正在尝试通过 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% 是静态的。

【问题讨论】:

  • 为什么不使用 cookie 或 localStorage,或者将值存储在 flash 范围/会话中,并将它们用于下一页
  • 我无权访问下一页。这是 SharePoint 上的一个表格,我厌倦了反复填写。大多数字段每次都将是相同的,所以我希望用脚本填写这些字段。有没有办法做你提到的任何事情?
  • 只有在 sharepoint 提供某种 API 后才能执行此操作,否则会导致严重的安全问题
  • 如果你愿意,你可以在apache中设置一个代理服务器,然后你就可以从sharepoint访问网页了。
  • 为什么不创建一个像 chrome 一样的扩展插件,然后你可以轻松地自动填充加载的网页 HTML 表单。

标签: javascript forms


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您正在尝试维护页面之间的状态。通常有两种方式来维护状态:

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

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

      示例:使用 Cookies

      使用 cookie,第一页必须将下一页所需的所有表单数据写入 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>
      

      示例:使用查询字符串

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

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

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

      <!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 的“散列”部分)中。

      第一个脚本与上面的查询字符串示例非常相似:重定向 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.

      【讨论】:

        【解决方案4】:

        这是一个使用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>
        

        【讨论】:

        • 我可能错了,但我认为我不能在我的情况下使用 cookie。为了让它们工作,我不需要通过下一页中的代码来访问它们吗?我无权访问第二页的源代码。这是一个我厌倦了每次填写的 SharePoint 表单。 90% 的字段值是静态的。我希望只用脚本设置值并提示输入标题,这样我就可以在下一页上单击“确定”。
        • @spassen 如果您的表单在您自己的服务器中,您可以为所欲为。可以使用 javascript 填充表单
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-27
        • 2013-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-20
        相关资源
        最近更新 更多