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.
You’re trying to maintain state between pages. Conventionally there are two ways to maintain state:
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:
… and the second page would then read those cookies and populate the form fields with them:
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:
…while the form would then parse the query string (available in JavaScript via
window.location.search– prepended with a?):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:… and then the form has to parse the fragment identifier etc:
And if you can’t edit the code for the form page
Try a greasemonkey script.