How to use JavaScript to fill a form on another page

前端 未结 4 1523
猫巷女王i
猫巷女王i 2020-11-29 05:08

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 a

4条回答
  •  心在旅途
    2020-11-29 05:25

    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:

    
    
     
         Maintaining State With Cookies
     
     
         
    Setting cookies and redirecting...

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

    
    
     
         Maintaining State With Cookies
     
     
         

    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:

    
    
     
         Maintaining State With The Query String
     
     
         
    Redirecting...

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

    
    
     
         Maintaining State With The Query String
     
     
         

    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:

    
    
     
         Maintaining State With The Fragment Identifier
     
     
         
    Redirecting...

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

    
    
     
         Maintaining State With The Fragment Identifier
     
     
         

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

    Try a greasemonkey script.

提交回复
热议问题