catch close browser with onunload function using master page in ASP.NET - asp.net

I have a website with master page. I want to catch a user trying to close the browser/tab. When I try using onunload in the body tag, it fires not only when I try closing the browser, but also when I navigate to another page.
Any idea how to only catch the event of closing the browser?

You can't distinguish closing the browser from navigating to another page. In both cases the current page is unloaded.
update: maybe you can handle some cases with some jquery, i.e. whenever a link is clicked, set some flag to be able to distinguish it from closing the window or entering a new URL:
<body onunload="checkForClose()">
...
<script>
var _isNavigation = false;
$(document).ready(function () {
// whenever a link is clicked set _isNavigation to true
$('a').click(function () {
_isNavigation = true;
});
});
function checkForClose() {
// show an alert if _isNavigation is not set
if (!_isNavigation) alert("closing the browser (maybe)");
}
</script>

Related

ReportViewerForMvc event on report load

I am loading a report in an iframe using ReportViewerForMvc. Currently, I have a spinner so that the user will know the report is loading. However, the spinner stops spinning when the iframe is placed on the page...not when the content of the report is finished rendering. I have found people using isLoading with $find but I am pretty sure that is just for asp and I need my to be in .Net
What is the simplest way to have spinner continue to spin until the report is loaded in the iframe?
Currently, I have a shared view for all reports that I am hoping to add some javascript to:
#using ReportViewerForMvc;
<div id="reportViewer">#Html.ReportViewer(Model.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)</div>
iframe onload does not work to stop spinner here.You would need cookies and client side script to accomplish that.
The server code will set the value in the cookie .Once the report is rendered the value will be read on the client side(cshtml) and spinner can be stopped.
Read this article.Here you can replace the blocker with the spinner.
http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/
//This should be called on the event when you are loading the report
//In your case you will route the url to controller or invoke the link
//for the report
$(document).ready(function () {
$('#create_pdf_form').submit(function () {
blockUIForDownload();
});
});
//This is where you will place the spinner
function blockUIForDownload() {
var token = new Date().getTime();
//use the current timestamp as the token value
$('#download_token_value_id').val(token);
$.blockUI();
fileDownloadCheckTimer = window.setInterval(function () {
var cookieValue = $.cookie('fileDownloadToken');
if (cookieValue == token)
finishDownload();
}, 1000);
}
//This will read the token generated from the server side controller or
//aspx.cs or ashx handler
function finishDownload() {
window.clearInterval(fileDownloadCheckTimer);
// $.removeCookie('fileDownloadToken'); //clears this cookie value
//$.cookie('fileDownloadToken', null);
//$.removeCookie("fileDownloadToken");
setCookie("fileDownloadToken", '2')
$.unblockUI();
}
//On the server side set the token , it could be controller or ashx handler
var response = HttpContext.Current.Response;
response.Clear();
response.AppendCookie(new HttpCookie("fileDownloadToken",
downloadTokenValue); //downloadTokenValue will have been provided in the
form submit via the hidden input field
response.Flush();
//Lastly don't forget to add these source js files.
<script src="~/Scripts/jquery-1.5.1.js"></script>
<script src="~/Scripts/jquery.blockUI.js"></script>
<script src="~/Scripts/jquery.cookie.js"></script>

Server side equivalent of "top.location.href"

I'm in 'Home' page. From there 'Child' page is called in a radwindow. Now on a click event of 'Child' page, I want to close the radwindow and reload page 'Home' page.
Inorder to achieve this, on the click event of a button defined in 'Child' page. I am calling a JavaScript function:-
function ReloadHome
{
var abc = 'Home.aspx';
top.location.href = abc;
}
Question:- How to close radwindow and then navigate or reload 'Home' page, using a server side method. Not the javascript mentioned above.
You can try with
Close :
Response.Write("<script language='javascript'> { window.close();}</script>")
Redirect :
Response.Redirect("...Your url");

asp.net mvc JavaScript in View User Controls rendered through regular browser request and AJAX request

I have this code in some of my ASCX files:
<%=Html.ActionLink(Resources.Localize.Routes_WidgetsEdit, "Edit", "Widget",
new { contentType = Model.ContentType, widgetSlug = Model.Slug, modal=true},
new
{
rel = "shadowbox;height=600;width=700",
title = Resources.Localize.Routes_WidgetsEdit,
#class = "editWidget"
})%>
Take note of that rel="shadowbox..." there. This is to wire up ShadowBox Lightbox clone for this ActionLink.
This works fine when user requests a page containing this User Control thru normal browser request. But I also render/build those View User controls trough AJAX requests. For instance, I would make request to /Widget/RenderToString/... using jQuery .ajax() method and it would return HTML code for that control. This works fine and it renders the code fine. I would then insert (append) the result to a DIV in a page from where the AJAX request was made. This also works fine and the returned HTML gets appended. The only problem is - ShadowBox is not wired up. Even though the code for it gets rendered.
It seems it requires page reload (F5) every time to wire ShadowBox up. Since I am doing AJAX GET and instant append to get rid of having to make a server roundtrip, I would also want ShadowBox to wire up without doing refresh.
Can someone help me with that? Thank you
UPDATE:
Yes, I have this in my Site.Master head:
<script src="<%=Url.Content("~/Scripts/shadowbox-build-3.0rc1/shadowbox.js") %>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
// insert functions calls here that provide some default behaviour
externalLinks();
});
Shadowbox.init({
language: "en",
players: ["img", "html", "iframe"],
onClose: function() { location.reload(true) }
});
</script>
How do I init the Shadowbox again after AJAX call?
There are many shadowbox plugins... which one are you using? (I can't give you exact code without it.) In any case I imagine you have something in your $(document).ready(function () { ... }); that tells shadowbox plungin to bind itself. You need to call that again after the AJAX call.
Just found the solution here
// call this after adding the new HTML to the page
// set up all anchor elements with a "editWidget" class to work with Shadowbox
Shadowbox.setup("a.editWidget", {});

Detect F5 being pressed and Refresh

I have a webform and i want to detect if F5 button was pressed or if the page was refreshed. I know about postback but it is not what i'm looking for. I have a gridview that loads in a modal popup when a button is clicked and a parameter's value is set for the gridview. When refresh is hit and if the modal popup button was previously clicked the modal popup is visible right after refresh. I want to detect if the page is refreshed to prevent this. any ideas? I thought to try Override but I'm not exactly sure how to use it. I tried Control.ModifierKeys but I don't have access to ModifierKeys.
Pressing F5 or physically clicking the browser refresh behaves similarly to navigating away from the page. This is captured in the event window.onunload. Try the snippet example below:
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
This will capture the refresh and allow you to do something or prompt the user.
Reemember that hotkeys are processed in the client side in the browser. The easiest way to implement this is through javascript.
Look at the following link:
http://snippets.dzone.com/posts/show/3552

ASP.Net Script Controls, Returning False from OnClick, and FireFox

Short Explanation:
I have a script control that has the click event being handled in the script file. The Click handler pops up a confirm prompt and returns the prompt's value.
Problem:
IE sees the return False (Cancel is selected on the confirm box) and there is no postback. Firefox ignores this and fires the postback.
Solution?:
I read that if I were doing this the old fashion way, I would need to have:
onClick="return SomeMethod();"
In the markup. There hopefully is a way to do this with script controls?
Example:
Here's what I have in the script file:
//THIS IS THE METHOD CLICK CALLS
handleLnkDeleteButtonClick: function(e)
{
var confirmed = confirm('This will delete the current Message category and move all messages to the Oprhan cataegory. Continue?');
return confirmed;
},
initialize: function()
{
this._lnkDeleteButton = $get(this._lnkDeleteButtonID);
this._lnkDeleteButton.idpicker = this;
//HOOK BEGINS HERE
this._lnkDeleteButtonClick = Function.createDelegate(this, this.handleLnkDeleteButtonClick);
$addHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
//END HOOK HERE
NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'initialize');
},
dispose: function()
{
$removeHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'dispose');
}
Ok so solved it myself after about way too much time trying to phrase things correctly for google. Turns out there is a method to call so that you don't have to worry about returning true or false.
handleLnkDeleteButtonClick: function(e)
{
var confirmed = confirm('This will delete the currery Message category and move all messages to the Oprhan cataegory. Allow?');
if (!confirmed)
{
e.preventDefault();
}
},
So instead of returning confirmed, I merely had to check it's value and call the e.preventDefault method to stop the click from firing.

Resources