open in new tab of browser programmatically - c#

i have a login page in fancy box and on click of login i want the secure pages open in the new tab
and uses this code
// on code at btnlogin_click
FormsAuthentication.RedirectFromLoginPage(loginID, false);
string redirectTo = GetResPath("/webPages/Default.aspx");
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "add2", "parent.jQuery.redirTo='" + redirectTo + "'; parent.jQuery.fancybox.close();", true);
//on aspx page
<script type="text/javascript">
$(document).ready(function () {
$('[id*=logn_btn_new]').fancybox({
'width': 480,
'height': 280,
'padding': 10,
'margin': 10,
'hideOnOverlayClick': false,
'scrolling': 'no',
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
'type': 'iframe',
'onClosed': function () {
try {
if ($.redirTo != null && $.redirTo.length > 0) {
var pop = window.open($.redirTo, '_newtab');
if (pop == null) {
alert("Please allow popups.");
}
}
}
catch (err) {
alert(err);
}
}
});
});
</script>
and redirTo is hidden fielld.
i am not able to open page in new tab can anybody help?

This is a difficult one, as it is something that is controlled by the user's web browser settings.
The method that you are using is specific to FireFox and will indeed open a new tab. But this can still be overridden by the user's settings.
However to get the same effect in other browsers here is an article for IE Open a new tab in IE through Javascript
It is worth considering why you need to do this. Users may be confused if you open a new tab / window without informing them. Is it possible to not open a new window and keep everything in the same page? Then you know that people logically will have the same results to an extent.
I hope this helps!

Related

Angular Web api file Download [duplicate]

HTML:
<a href="mysite.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
Uploads get a unique file name while there real name is kept in database. I want to realize a simple file download. But the code above redirects to / because of:
$routeProvider.otherwise({
redirectTo: '/',
controller: MainController
});
I tried with
$scope.download = function(resource){
window.open(resource);
}
but this just opens the file in a new window.
Any ideas how to enable a real download for any file type?
https://docs.angularjs.org/guide/$location#html-link-rewriting
In cases like the following, links are not rewritten; instead, the
browser will perform a full page reload to the original link.
Links that contain target element Example:
link
Absolute links that go to a different domain Example:
link
Links starting with '/' that lead to a different base path when base is defined Example:
link
So in your case, you should add a target attribute like so...
<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
We also had to develop a solution which would even work with APIs requiring authentication (see this article)
Using AngularJS in a nutshell here is how we did it:
Step 1: Create a dedicated directive
// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
restrict: 'E',
templateUrl: '/path/to/pdfDownload.tpl.html',
scope: true,
link: function(scope, element, attr) {
var anchor = element.children()[0];
// When the download starts, disable the link
scope.$on('download-start', function() {
$(anchor).attr('disabled', 'disabled');
});
// When the download finishes, attach the data to the link. Enable the link and change its appearance.
scope.$on('downloaded', function(event, data) {
$(anchor).attr({
href: 'data:application/pdf;base64,' + data,
download: attr.filename
})
.removeAttr('disabled')
.text('Save')
.removeClass('btn-primary')
.addClass('btn-success');
// Also overwrite the download pdf function to do nothing.
scope.downloadPdf = function() {
};
});
},
controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
$scope.downloadPdf = function() {
$scope.$emit('download-start');
$http.get($attrs.url).then(function(response) {
$scope.$emit('downloaded', response.data);
});
};
}]
});
Step 2: Create a template
Download
Step 3: Use it
<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>
This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.
Our example uses PDF files, but apparently you could provide any binary format given it's properly encoded.
If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.
I hope it, will be helpfull.
HTML :
<i class="fa fa-file-excel-o"></i>
DIRECTIVE :
directive('fileDownload',function(){
return{
restrict:'A',
scope:{
fileDownload:'=',
fileName:'=',
},
link:function(scope,elem,atrs){
scope.$watch('fileDownload',function(newValue, oldValue){
if(newValue!=undefined && newValue!=null){
console.debug('Downloading a new file');
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isBlink = (isChrome || isOpera) && !!window.CSS;
if(isFirefox || isIE || isChrome){
if(isChrome){
console.log('Manage Google Chrome download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var downloadLink = angular.element('<a></a>');//create a new <a> tag element
downloadLink.attr('href',fileURL);
downloadLink.attr('download',scope.fileName);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
}
if(isIE){
console.log('Manage IE download>10');
window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName);
}
if(isFirefox){
console.log('Manage Mozilla Firefox download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var a=elem[0];//recover the <a> tag from directive
a.href=fileURL;
a.download=scope.fileName;
a.target='_self';
a.click();//we call click function
}
}else{
alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
}
}
});
}
}
})
IN CONTROLLER:
$scope.myBlobObject=undefined;
$scope.getFile=function(){
console.log('download started, you can show a wating animation');
serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
.then(function(data){//is important that the data was returned as Aray Buffer
console.log('Stream download complete, stop animation!');
$scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
},function(fail){
console.log('Download Error, stop animation and show error message');
$scope.myBlobObject=[];
});
};
IN SERVICE:
function getStream(params){
console.log("RUNNING");
var deferred = $q.defer();
$http({
url:'../downloadURL/',
method:"PUT",//you can use also GET or POST
data:params,
headers:{'Content-type': 'application/json'},
responseType : 'arraybuffer',//THIS IS IMPORTANT
})
.success(function (data) {
console.debug("SUCCESS");
deferred.resolve(data);
}).error(function (data) {
console.error("ERROR");
deferred.reject(data);
});
return deferred.promise;
};
BACKEND(on SPRING):
#RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
#RequestBody Map<String,String> spParams
) throws IOException {
OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
in template
<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
system_update_alt
</md-icon></md-button>
in controller
$scope.export = function(){ $window.location.href = $scope.export; };

How to display the content in popup window?

Iam creating a button "SampleTest", which wil have to show the model data and "GoBack" button in popup window.But it displaying the content in full screen popup also overriding.Like,
i have my jquery like,
$('#SampleTest').button().click(function () {
var options = {};
options.type = "POST";
options.url = "/Dashboard/SampleTest/";
options.dataType = "json";
options.contentType = "application/json";
options.success = function (data) {
alert(data);
$(".popup").html(data);
$(".trasparentDiv").show(data);
$(".popup").show(data);
};
$.ajax(options);
});
Do i need to include any function in my jquery for popup window.Kindly tell me what to do in this case.
Please include JQuery UI script with appropriate version into your page after JQuery core script file.
Jquery UI CDN Path from JQuery: https://code.jquery.com/ui/
More help about Jquery Popup: http://jqueryui.com/dialog/
i have rewritten the code like,
function LoadSampleTest() {
alert('sample');
$("<div></div>")
.attr('id','SampleQuestionDiv')
.appendTo("body")
.dialog({
modal: true,
Close: function () {
$(this).dialog("close");
},
Width: 1000,
height: 800,
title: "Sample Test"
}).load("/dashboard/sampletest/");
Its works good.Instead of OK button, i have given close option to close the popup.

How to close browser window with a dialog popup using jQuery function?

I am working on a project but need to know how to close the browser window and also show a dialog box if I would like to exit the page, using jQuery.
Thanks Rick, this helps, it brings up the dafault chrome pop up dialog, I am trying to customize it to use my dialog in my javascrip file so it can prompt it when the user closes the page.. here is my code function ConfirmationDialog(baseURI) {
var dialog = jQuery('Are you sure you want to exit this form without saving?').attr({
type: 'hidden',
id: 'dialog'
}).css("display", "none").appendTo('body');
jQuery("#dialog").dialog({
resizable: false,
height: 140,
modal: true,
title: 'Confirm',
buttons: {
"Yes": function () {
window.location = baseURI;
// jQuery(this).dialog("close");
},
Cancel: function () {
jQuery(this).dialog("close");
}
}
});
return false;
}
To close browser:
window.close();
To prompt user:
window.addEventListener("beforeunload", function (e) {
var message = "Are you sure you want to leave?";
(e || window.event).returnValue = message;
return message;
});

Redirect parent page to specified url on Submit inside fancybox

i am using fancybox and after submiting my form i want to redirtect my parent page to some specified url i am using fancybox as below
$(document).ready(function () {
$('[id*=addnewRequest]').fancybox({
'width': 760,
'height': 540,
'padding': 0,
'margin': 0,
'hideOnOverlayClick': false,
'scrolling': 'auto',
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
'type': 'iframe',
'centerOnScroll': true,
'onClosed': function () {
if ($.redirTo != null && $.redirTo.length > 0){
window.location.replace($.redirTo);
}
else {
parent.location.reload(true);
}
}
});
});
and after submiting my form i am using below register script where 'redirectTo' is url where i want my parent page will redirect
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "add", "parent.jQuery.redirTo='" + redirectTo + "'; parent.jQuery.fancybox.close();", true);
Now how my parent page will redirect to perticular url.Any idea?
thanks,
After submiting your form you can direct call the window.top.location.href with the new url as:
window.top.location.href = "http://www.urltogo.com/pagetomove.aspx";
and avoid to send parameters on the parent and from there make the redirect.
Here is an example (I add 5 second delay to have the time to see it)
http://jsfiddle.net/u6whQ/3/ or http://jsfiddle.net/u6whQ/4/
Your line will probably be as:
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "add", "window.top.location.href ='" + redirectTo + "'; parent.jQuery.fancybox.close();", true);

Session expires after closing jquery dialog

In my web application I use jquery dialogs to open popups.
The function used to perform this task is this:
function OpenPopup(popupTarget, width, height, params, onOpenFunction, onCloseFunction, popupElement){
// some code to parse the parameters
//`popupElement` is a div with `style="display: none;"`
// included in a master page which every page inherits from
$(popupElement).dialog(
{
autoOpen: false,
resizable: false,
height: height,
width: width,
modal: true,
open: onOpenFunction,
closeOnEscape: false,
close: function (e)
{
var popupResult = $(this).dialog("option", "notification");
$(this).dialog("destroy");
if (!isHTMLElement)
popupFrame.css("visibility", "hidden");
if (jQuery.isFunction(onCloseFunction))
{
var funct = eval(onCloseFunction);
funct(popupResult);
}
}
});
$(popupElement).dialog("open");
}
This is the function that calls the above method:
function FiltroNotifiche(){
params = "";
OpenPopup("~/manage/Popup/FiltroNotifiche.aspx", 450, 350, params, function (e) { }, function (strNotification)
{
OnPopupReturn(true, strNotification, function ()
{
__doPostBack('UpdatePanel', 'Filtro=true');
});
});
}
function OnPopupReturn(bRefresh, strNotification, senderFunction){
// this function parses strNotification and if, successful, calls:
var funct = eval(senderFunction);
funct();
}
Inside the popup I use the ICallbackEventHandlercallback interface.
The problem is that after opening and closing the popup (I can see the callback being executed and all), whatever I do next I'm getting kicked out, most likely because the session has expired.
A strange thing that I noticed is that this happens only if I get to the page that opens the popup (GestioneNotifiche.aspx) via the menu control, because if I get to there through a button PostBackUrl in another page, this doesn't happen, and the session lives happily!
The menu has an xml data source and these bindings:
<DataBindings>
<asp:MenuItemBinding DataMember="Menu" TextField="Text" Selectable="false" />
<asp:MenuItemBinding DataMember="MenuItem" NavigateUrlField="NavigateUrl" TextField="Text" ValueField="Value" />
</DataBindings>
This is the menu item:
<MenuItem Value="" Text="Gestione notifiche" NavigateUrl="~/manage/GestioneNotifiche/GestioneNotifiche.aspx" />
I did notice the call through the menu has Request.HttpMethod = "GET", while via postback it is (rather obviously) "POST". Could this be the significant? I don't really know much about the difference between GET and POST.
Thank you
Sounds like your problem is that authentication is being cleared and not your session. Check your page_load event to see if you are doing anything differently between a GET and POST request that would result in clearing the authentication.

Categories

Resources