Change form target to _blank with primefaces and oncomplete - javascript

This topis is already present in other posts but none of the solutions mentioned worked for me so here I am, hoping someone can point me in the right direction.
Basically, I have an application with Primefaces 3.5 with 2 commandButtons that execute backing bean methods to generate two different reports as an output stream (no GET available). One of this report is generated as attachment while the other one should be displayed in another tab. Both in the same form.
My problem comes with the report generated in a separate tab: since the reports share the same form, I cannot use target=blank in the form definition and since I have to do validations in my backing bean, I must show possible error messages in the main tab, opening the new one only in case everything goes smoothly.
I tried the following js in the form page:
function test() {
document.getElementById("formRep3_1").target = '_blank';
}
called by the bean with
RequestContext.getCurrentInstance().execute("test()");
after validation successful. But it doesn't work.
I also tried setting an oncomplete="test()" on report button, slightly modifying the js like this:
function test() {
var v = '<h:outputText value="#{repReqStatus.resultCheck}" />';
if (v.value == "success") {
document.getElementById("formRep3_1").target = '_blank';
}
else {
alert('no');
}
}
but it seems the oncomplete doesn't get called at all! Not even if I do another check like
oncomplete="if (!args.validationFailed){test()}"
So yeah, I'm lost. Any help is really appreciated.
Thanks!

You can't change the link's target during invoking the link's action. It's too late.
Your best bet is to keep out the target="_blank" and instead invoke a JavaScript window.open() on the desired URL. You can store the PDF report in session, or prepare request parameters for the URL so that it can generate the desired PDF report based on those request parameters.

Related

Contact Form 7 not redirecting upon email sent

I have a form that I am trying to have redirect to http://www.example.com upon successfully sending an email. I have tried different approaches including on_sent_ok in the additional settings as well as
if(jQuery('.wpcf7-mail-sent-ok').length > 0)
window.location.replace("http://stackoverflow.com");
in my JavaScript, but that does not seem to work as well.
Edit: I forgot to mention that upon the user clicking submit, I do a prevent default in order to do some calculations and generate a PDF. Once it is all done I do
$("form.wpcf7-form").unbind('submit').submit();
to allow the submission to happen. Could this be causing any issues with the redirection?
Contact Form 7 made a ajax call. After success the element is inserted. Then you can check if element exist:
jQuery(document).ajaxComplete(function() {
if (jQuery('.wpcf7-mail-sent-ok').length) {
alert(1);
//window.location.replace("http://stackoverflow.com");
}
});
Well, maybe I'm writing late, but this code will definitelly will do the job. (If you're working in wordpress). I'm using it so far and it's working normally.
Remember to place this code at your functions's file and as final note remember that you must use one or the other, not both...!
add_action('wp_head', 'RedirectsCF7');
// Start of function.
function RedirectsCF7() {
if(is_page("contact-page-or-whatever-page-name-is")) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
// Or simply add this code to all pages, like this.
if(!is_admin()) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
Reference here

Can't seem to retrieve session value or control value on .aspx page javascript function

Wonder if anyone can help as im really stuck on a problem i'm having
Using vb.net I have a web application with several .aspx pages.
on one of my aspx pages I have a javascript function that i want to retrieve a pdf path from a session value i set within code behind. After searching the web everywhere seems to say use something like the following
var pdf_link = '<%=Session["pdfpath"].ToString() %>';
here is the javascript function:
function showmodal() {
var pdf_link = '<%=Session["pdfpath"].ToString() %>';
var iframe = '<div class="iframe-container"><iframe src="' + pdf_link + '"></iframe></div>'
$.createModal({
title: 'PDF Preview',
message: iframe,
closeButton: true,
scrollable: false
});
}
to get the value but i get an error message before i can even compile 'Identifier Expected' and it highlights between the [" as being the problem area. i just can't get this to work what am i doing wrong.
Also because i couldn't workout what was wrong with the above i have tried saving the value i want into a hidden field and tried to access that using the following
document.getElementById("PdfPathHiddenField").value
but that just returns null all the time. I just can't seem to access anything within my javascript function.
What i also see as odd is for instance when debugging i have say page1.aspx and page2.aspx. From page1.aspx in code behind on a button click i use
Response.Redirect("~/page2.aspx")
When I have stopped the debugger within my javascript function on page2.aspx to retrieve the value i notice that the tab with the code where the debugger has stopped for page2.aspx is titled page1[Dynamic] but it is the correct source from page2.aspx not page1.aspx really confused as shouldn't it say page2[Dynamic] on that - is this why i maybe can't seem to access any controls as it thinks it's elsewhere ???? Help
Thanks in advance any help would be much appreciated.
In VB.NET arrays have parentessis, Session("pdfpath").ToString(), in C# or javascript you can use square brackets, but not in VB.
PS: Remeber to mark this an answer if it's a solution for your problem

Preventing XSS Attack on Form

All:
I have an issue with a project I am working on using C# MVC4
In the project, I am accepting a URL and other parameters from a user, then do some processing and send the result of the processing to the URL provided by the user.
The result is being sent using the following code:
var context = HttpContext.Current;
context.Response.Write("<html><head>");
context.Response.Write("</head><body>");
context.Response.Write(string.Format("<form name=\"myform\" method=\"post\" action=\"{0}\" >", postUrl));
context.Response.Write("</form>");
context.Response.Write("<script type=\"text/javascript\">document.myform.submit();</script></body></html>");
context.Response.Write("</body>");
context.Response.Flush();
context.Response.Clear();
context.ApplicationInstance.CompleteRequest();
Whenever a user attempts an XSS like passing a url value of javascript%3aalert('xss')%2f%2f, the JavaScript runs and the pop up shows up.
I've tried Antixss.HtmlEncode() to encode the URL before passing it into string.Format but still doesn't work. I've tried Antixss.UrlEncode() also, but this gives error as the form doesn't submit to the URL.
Please help me out, Is there something I am missing? What else can I do?
Thanks in advance.
You will need a three pronged approach to solve this issue.
Preventing XSS injection:
Note that if a user injected the url value
" /> <script>alert('xss')</script>
this would also leave you vulnerable:
<form name="myform" method="post" action="" /> <script>alert('xss')</script>" >
Therefore you should use the HttpUtility.HtmlAttributeEncode function to solve this one.
However, don't stop there. As noted, you should project against javascript: style URLs. For this I would ensure that the URL begins with http:// or https://. If not, throw a SecurityException which you should be logging and handling server-side, and showing the user a custom error page.
Finally, you want to protect against Open Redirect Vulnerabilities. This is to stop phishing attacks by redirecting users to other domains. Again, use a whitelist approach and ensure that the domain redirected to is one of your own. Be careful on the parsing here, as it is easy to get it wrong - a URL of http://example.org?http://example.com will pass the validation filter for example.com on many badly written validation routines. I recommend using the Uri object in .NET and retrieving the domain through that rather than rolling your own string functions.
You could also check if the URL is a relative URL, and allow it if acceptable. Use something like this function which uses a built in .NET library to ensure that it is relative or not.
Just a thought - try putting this script in rather than just document.myform.submit (and remove the form's action property):
if("{0}".indexOf('http') !== 0) {
//this is some sort of injection, or it's pointing at something on your server. Should cover http and https.
//Specifically, it makes sure that the url starts with 'http' - so a 'javascript' url isn't going to work.
} else {
document.myform.action="{0}"
document.myform.submit();
}
There is more you could do, but this should help.
Since you are adding the postUrl as an attribute "action" of the form tag, you can try using HtmlAttributeEncode method in the HttpUtility
[ValidateInput(false)]
public ActionResult Test(string url)
{
var context = System.Web.HttpContext.Current;
context.Response.Write("<html><head>");
context.Response.Write("</head><body>");
context.Response.Write(string.Format("<form name=\"myform\" method=\"post\" action=\"{0}\" >", HttpUtility.HtmlAttributeEncode(url)));
context.Response.Write("</form>");
context.Response.Write("<script type=\"text/javascript\">document.myform.submit();</script></body></html>");
context.Response.Write("</body>");
context.Response.Flush();
context.Response.Clear();
context.ApplicationInstance.CompleteRequest();
return null;
}
http://localhost:39200/home/test?url=https%3A%2F%2Fwww.google.com - Worked
http://localhost:39200/home/test?url=%3Cscript%3Ealert(%27test%27)%3C%2Fscript%3E - Worked(Did not show alert)
It is always good practice to Validate the user input against a white list of inputs, to prevent XSS exploits.
try using HttpUtility.UrlEncode
something like Response.Write(HttpUtility.UrlEncode(urlString));
see How To: Prevent Cross-Site Scripting in ASP.NET for more steps =)

How to execute some jQuery or JavaScript code after a redirect has completed

How can I execute jQuery/JS code as soon as a jQuery/JS redirect like...
$(location).attr('href','/target_path');
...or...
window.location.href = "/target_path";
...has finished loading the new page?
Specifically, I need to pass an alert message and insert it into and display it (enclosed in some HTML) on the new page.
You can't. Once the redirect happens you are no longer on that page. You can't execute code on a page you are no longer on. If you want the next page to do something then you need to pass, either by cookie or URL parameter, a flag that instructs it to do so.
It is impossible to tell JavaScript to execute some code after a redirect.
However you have different options:
Pass a string in the redirect URL and then do something on "ready"
Store some information in a cookie and then do something on "ready"
Store some data using DOM storage (namely sessionStorage) if you don't mind the smaller browser support
You can't do that in the page that's redirecting. You can read the referrer in the landing page (document.referrer), and then decide whether to display an alert based on that, though.
var x = "It's some text";
var loc = '/target_path';
loc += '?message=' + encodeURI(x);
The JS file on the new page can then look at the query string to see if a message is there, and do the required action if it's detected.
You can use window.location.search on the new page to see what's there, although I'd recommend hunting for a deparam function in a library to turn the query string into a more usable object.

How to add parameters to a #Url.Action() call from JavaScript on click

I have a link that when clicked needs to call a controller action with certain data which must be retrieved via JavaScript. The action will be returning a FileStreamResult.
I looked at #Url.Action but I couldn't figure out how (or even if) I could pass value dictionary stuff which had to be retrieved via JS.
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
So any help on how you would do something like this would be great..
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
Exactly. You can't do much with a received byte in javascritpt: obviously you cannot save it on the client computer nor pass it to some external program on the client. So don't call actions that are supposed to return files using AJAX. For those actions you should use normal links:
#Html.ActionLink("download file", "download", new { id = 123 })
and let the user decide what to do with the file. You could play with the Content-Disposition header and set it to either inline or attachment depending on whether you want the file to be opened with the default associated program inside the browser or prompt the user with a Save File dialog.
UPDATE:
It seems that I have misunderstood the question. If you want to append parameters to an existing link you could subscribe for the click event in javascript and modify the href by appending the necessary parameters to the query string:
$(function() {
$('#mylink').click(function() {
var someValue = 'value of parameter';
$(this).attr('href', this.href + '?paramName=' + encodeURIComponent(someValue));
return true;
});
});
Instead of going with a post, I'd go with associate a JQuery on click handler of the link which would call the controller action. This is assuming that the action method returns a FileStreamResult and sets the correct content type so that the browser interprets the result and renders it accordingly.
With your approach you'd have to interpret in the onSuccessHandler of the post on how to render the generated stream.

Categories