simple javascript works in console but not greasemonkey - javascript

I'm just trying to submit the already-filled-out login form at this site:
http://portal.mypearson.com/mypearson-login.jsp
In firefox console, I can type this:
doSubmit();
and it works fine but it doesn't work in greasemonkey. By 'doesn't work' I mean nothing happens. I can do document.forms[0].submit() but the page comes back complaining that the user and pass variables aren't set correctly.
What do I need to do to get the script that works in console to work in greasemonkey?

Have you tried taking the functionality from the doSubmit() function and performing those actions?
A quick inspection of the code looks like this:
if (!validate(displayForm)) {return false;}
loginForm.loginname.value = displayForm.loginname.value;
loginForm.password.value = hex_md5(displayForm.password.value.toLowerCase());
loginForm.encPassword.value = 'Y';
loginForm.submit();
return true;
It looks like the form is actually just copying its values to another form and then submitting the other form.
You could first start by removing the onsubmit event by using:
displayForm.setAttribute("onsubmit", null)
Or you could just bypass the display form all together and go straight to the source. Your greasemonkey script would look something like this without all the extra steps:
// Setup your authentication values here
var username = "(Your user name)";
var password = "(Your password)";
// Add your variables to the submit form
loginForm.loginname.value = username;
loginForm.password.value = hex_md5(password.toLowerCase());
loginForm.encPassword.value = 'Y'
// submit the form
loginForm.submit();
That will bypass the form that is displayed to the user all together.
Hope that helps.

Related

How do you get URL parameters in a Google Form using Google Apps Script?

So I've got a Google Form where I'd like to pass in a parameter from an email link like this:
https://docs.google.com/URL/forms/d/LONGSTRING/viewform?id=12345
I'd like to be able to grab that id and pass it into the spreadsheet recording results. Now I've got writing to a spreadsheet down, but getting the id is problematic.
I've already tried:
function doGet(e) {
var id = e.parameter.id;
Logger.log(id);
}
and
function doPost(e) {
var id = e.parameter.id;
Logger.log("do post " + id);
}
Both of which throw errors when I view the execution transcript, which I suspect is because they're designed to run within deployed webapps.
Additionally, I've tried using plain old javascript to do something like:
var formUrl = window.location.href;
var formId = formUrl.split('?id=')[1];
which also throws errors when you view the execution transcript .
Any other ideas?? Maybe I can get the information in another way?
I think you can't use your own id, you have to use the id of the Google Form's "Item" object. You can figure out the id by viewing a prefilled form. In the Form edit screen, click "Responses", "Get Pre-filled URL". Fill in the field that you want to use and click Submit. On the new page, you are given a URL in "Share this link to pre-fill the responses" . Examine that url and you can see "get" arguments like ?entry.265525444=mytext . Replace mytext with whatever you want to be in the field.
This will display the field on your form, however. I myself was searching for how to make such a field readonly or invisible when I got here, but I hope this shows you a new direction to try.
I am assuming you are trying to get the form id?
You will need to set up a trigger that will run on form submit.
function onSubmit(){
var form = FormApp.getActiveForm();
var formID = form.getId();
}

How to find the URL of an external site's Javascript submit

I will do my best to try to explain this.
I am scraping a website for it's elements to then output in a different format. The problem that I am experiencing is the way that this site directs the user throughout the site is through a Javascript redirect.
When checking the 'a href' tag, this is the Javascript that shows up
javascript:doParamSubmit(2100, document.forms['studentFilteredListForm'], 'SSC000001MU9lI')
The SSC000001MU9lI changes for each element that it redirects to.
Is it possible to find a URL using this Javascript, so that I can reach the HTML page externally?
EDIT: Here is the doParamSubmit and doSubmit classes:
function doParamSubmit(event, form, parameter) {
form.userParam.value = parameter;
doSubmit(event, form);
}
function doSubmit(event, form)
{
// Make sure if something fails that the form can be resubmitted
try
{
// If this form has not been submitted yet... (except for IE)
if (allowSubmit == true && form != null && (submitted == false || isInternetExplorer6() || isInternetExplorer7()))
{
submitted = true;
form.userEvent.value = event;
// Fix for IE bug in which userEvent becomes a property array.
if (form.userEvent.length)
{
form.userEvent[0].value = event;
}
// Disable the form so the user can't accidentally resubmit the page
// (NOTE: this doesn't disable links (e.g. <a href="javascript:...">)
disableForm(form);
// If there is a populate form function, call it. If there are spell check fields on the
// page, populateForm is used to set hidden field values.
if (this.populateForm)
{
populateForm();
}
saveScrollCoordinates();
// resetSessionTimeout();
try
{
form.submit();
}
catch(e)
{
// Exceptions thrown here are only caused by canceling the submit in onbeforeunload, so ignore.
submitted = false;
}
}
if (allowSubmit == false)
{
alert(grabResource("message.pageLoading"));
}
}
catch(e)
{
submitted = false;
throw e;
}
}
I see 2 approaches.
You use a javascript enabled browser such as http://nrabinowitz.github.io/pjscrape/. I am not sure if you intend to just follow the links or instead grab the URL for some other use so your mileage may vary.
Find the doParamSumit() function in their page/scripts and analyze it to understand how it gets the URL - the one you have as an example looks like it grabs the action from a form perhaps? Once you know how the function work you might be able to harness that info in your scraping by using some regex to find URLs that match the doParamSubmit pattern and going from there. It's hard to say without seeing the function itself as well as the other links like it though.
Regardless of which method you choose I would begin by understanding the function - look for it in the code or loaded js files (you can also you things like javascript debuggers on most browsers to help you find it) and see what happens - it might be super obvious.
Also keep in mind that this might be a POST for a form - in which case the result of you following that link may not work if it expects valid form data.
Edit I see that you posted the function. It simply submits the form listed in the second parameter i.e. 'studentFilteredListForm'. While I don't think your scraping will go to far chasing forms you can still get the URL either with javascript if your scraper lets you (something like $('form[name=studentFilteredListForm]').attr('action') or using whatever language your are using for the scraper i.e. find the form and extract the action url (remembering that if there is no action it is probably posting back to the current URL)
But again... you might first manually get the URL of the form and see where that gets you. You might just get a page with form errors :)

collect data from a form hosted on another site

We have a number of clients that have agreed to send us their form data once a form is submitted on their site. Is this possible and what is the best way to handle this? Our site is built in coldfusion while the client site varies.
I had the client add a script tag to include a javascript file from our server on their form page. Also had them add an onClick event to their form button so this javascript is called on submission of their form.
This is the javascript file:
function cpcshowElements(f) {
var formElements = "";
for (var n=0; n < f.elements.length; n++) {
box = f.elements[n];
formElements += box.name + ":" + f.elements[n].value + ",\n";
}
var track = new Image();
/*send data to us*/
track.src="http://XXX.net/form_record.cfm?form="+ formElements + "&self=" + this.location;
}
On form submission the cpcshowElements function is called, formats the form data, appends it to the end of the XXX.net/...and calls that url. The form_record.cfm page basically does some checks and inserts the data into a table.
This process does work, however not consistently. The data doesn't always make it into the database. That is the problem. Is there another way to do this that won't have data loss?
The data getting to the database is pretty deep down the chain. The first step is to figure out where the request isn't coming through. Find the weak link, and then fix that part.
Chances are, there are other issues causing the failure than this piece of javascript. Test each part of the process and figure out where the problem lies. Chances are, it isn't in the javascript.
Check whether the form on the serve is being submitted by method other than onClick. If the form can be submitted by hitting enter or tabbing and hitting enter or the spacebar, than you are missing some submits. Would work more consistently with onSubmit rather than onClick.
Example:
<form onsubmit="your_function_here">
Also, if the form is submitting and then moving on to another page, you javascript code may not have enough time to fire. In that case, put a delay into your function to allow the GET request for the image to be made before the page evaporates.

How to continue running execution after form submit?

I am writing a simple form submit function for a specific site.
The script fills the specific form on the current page and submits the form. It MUST also fill the second form which appears after the first form is submitted and submit this form too.
That is there are 2 forms that must be filled and submitted.
Problem however, is that on a normal page the script fills and 1st form and submits it. After submission however, the script stops working! I want to continue execution!
I've done it by mistake on a page that had 2 frames! most pages don't have frames!
function FillFirstForm(){
doc=document;
//Some code removed from above...Fill Values
doc.forms[0].name.value = answerarray[1];
doc.forms[0].address.value = answerarray[2];
doc.forms[0].phone.value = answerarray[3];
doc.forms[0].username.value = answerarray[4];
//And Press Button
doc.forms[0].submit.click();
iTimer=setInterval(FillSecondForm,5000);
return true;
}
function FillSecondForm(){
clearInterval(iTimer);
doc.forms[0].tags.value = answerarray[5];
doc.forms[0].reference.value = answerarray[6];
document.forms[0].submit.click();
return true;
}
The basic rule is that a classical form submission halts all execution of scripts of the page, and loads the next page. No way to do anything about that.
You may have to switch to sending your form's contents using Ajax. That will leave the current page alive, and allow you to do as many submits as you want to.
A very easy way to achieve this is the jQuery form plugin. It takes much of the manual hassle out of the process.
Can you call FillSecondForm() function on body load of second form, once first form submitted.
You could POST the first form with AJAX, and then submit the second form after receving the response for the first form.
Something like this perhaps:
function FillFirstForm() {
var post_data = 'name='+escape(answerarray[1]);
post_data += '&address='+escape(answerarray[2]);
post_data += '&phone='+escape(answerarray[3]);
post_data += '&username='+escape(answerarray[4]);
// TODO: make this cross browser :)
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if ( req.readyState == 4 ) { // The request has finished
if ( req.status == 200 ) {
FillSecondForm();
}
else {
// Deal with errors here
}
}
};
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.open('POST', '/submit_url', true);
req.send(post_data);
}
W3 schools has a tutorial on AJAX here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp, and there are many more on the web.

Calling JS Function on Form Submit

I have created a JS function which executes fine when it's included an the 'onclick' action of standard HTML link tag as follows:
test
However where I really want to use this function is on the 'onsubmit' action of a form but when I include it as follows the function no longer seems to be executing:
<form action="page.pl" id="disable-submit" name="status-form" method="POST" onsubmit="return fb_CheckPermission('publish_stream');">
What the 'fb_CheckPermission()' JS function basically does is use Facebook Connect to check to make sure the user has granted us a specific permission and if not it tells Facebook Connect to prompt the user to grant the permission. Here is the code for the JS function:
1. function fb_checkPermission(permission) {
2. FB.ensureInit(function() {
3. FB.Facebook.apiClient.users_hasAppPermission(permission, function (hasPermissions) {
4. if(!hasPermissions){
5. FB.Connect.showPermissionDialog(permission,function (status){
6. if(!status) {
7. if(permission == 'offline_access') {
8. // save session
9. }
10. }
11. });
12. }
13. });
14. });
15.}
What this code does is as follows:
Line 2: Make sure Facebook Connect JS library is loaded
Line 3: Checks to see if the current Facebook Connect user has granted a specific permission
Line 5: If the permission hasn't been granted then prompt the user with the permission dialog
Line 7: In the case of the 'offline_access' permission save the session key once granted
The user experience I'm trying to achieve is that when a user submits the form I'll check to see if they have granted a specific permission and if not prompt them for the permission before submitting the form. If the user has already granted the permission the form should just submit. For those users who are prompted the form should submit after they either choose to grant the permission or if the deny the request which I believe the fb_checkPermission() JS function is handling correctly right now. What I'm not sure is if there is some kind of JavaScript issue with how this works on form submission.
As I mentioned, this JS function works perfectly as an onclick action but fails as an onsubmit action so I'm pretty sure that this has something to do with how JavaScript treats onsubmit actions.
I'm stuck so I really appreciate your help in figuring out how to change the JS function to produce my desired user experience. Thanks in advance for your help!
The reason your "click on anchor" works is because it does not change your page (location) while all of the Facebook asynchronous calls finish.
When you attach the same function to the submit handler the function returns before Facebook stuff gets actually executed, and it does without returning "false" causing the form to proceed with submission earlier than you want it to.
What you need to do is return "false" at the end of your onSubmit function to prevent submission and give time to Facebook stuff to finish and then manually submit form at places you want it to be submitted by calling:
document.getElementById('disable-submit').submit();
(The handler will not be called if submittion is triggered from the script.)
Unfortunately I don't have Facebook SDK at hand so I can't write the code that I'm sure works 100%, but it's something along these lines:
function onSubmit () {
doStuffAsynchronously(function () {
if (everythingIsOK) {
// proceed with submission
document.getElementById('formId').submit();
}
});
return false;
}
Try putting the javascript call on the input you are using to initiate the submit.
I think basically that your browser tends to use default validation form (page.pl / method POST) instead of doing what you think it does
Try this
<form action="page.pl" id="disable-submit" name="status-form"
method="POST" onsubmit="returnFbChPermissionAndPreventDefaultAction();">
<script type="text/javascript">
var returnFbChPermissionAndPreventDefaultAction = function(){
//prevent default
if (event.preventDefault) {
event.preventDefault();
}
//specific for IE
valueOfreturn = fb_CheckPermission('publish_stream');
event.returnValue = valueOfreturn;
return event.returnValue ;
}
</script>

Categories

Resources