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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12183572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:20:52  来源:igfitidea点击:

How to use JavaScript to fill a form on another page

javascriptforms

提问by spassen

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.

我正在尝试通过 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>

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

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

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.

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

回答by Richard JP Le Guen

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
  • 在 cookie 中存储状态
  • 在查询字符串中存储状态

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.

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

Example: Using Cookies

示例:使用 Cookie

Using cookies, the first page would have to write all the form data you'll need on the next page to 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>

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

...然后第二页将读取这些 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>

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:

在使用查询字符串的情况下,第一页只会在重定向 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>

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

...而表单将解析查询字符串(在 JavaScript 中可用,通过window.location.search- 前置 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).

还有一个选择:由于状态是在客户端(而不是服务器端)严格维护的,您可以将信息放在片段标识符中(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:

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

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

尝试一个greasemonkey 脚本。

回答by Ibu

It is a good place to use cookies

这是一个使用cookies的好地方

Ex: From quirksmode.org

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

和旁注,您可以使用 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>

回答by Zec

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 clickHymaning! I do not want your script to tell the form of my bank what to do. ;-)

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

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.

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