This seems like a common question but search is not returning anything.
I have the following code that executes before the page unloads.The problem is if the unload is a postback i do not want to fire my warning to the user but i can't figure out how to differentiate between a postback and a user navigating to another page for example.
// This is executed before the page actually unloads
$(window).bind("beforeunload", function () {
if (prompt) {
//prompt
return true;
}
else {
//reset our prompt variable
prompt = true;
}
})
Running script in the code behind i.e. if Page.IsPostBack then set prompt is not an option.
Any ideas?
EDIT:
Here is the solution I ended up with:
function DoNotPrompt() {
prompt = false;
}
I then added this to all the controls where the user could do something that result in a post back.
OnClientClick="DoNotPrompt()
Then checked this flag and only returned a string in "beforeunload" if the user was really moving away from the page i.e. not a postback.
I also had to use this code:
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
prompt = false;
}
The reason being i had a custom user control that was a list box and I could not add the above method. So used this to catch that event and set the flag to false.
Not the most elegent solution.
Thanks,
Michael
You can capture the submit and reset the onbeforeunload as:
jQuery(function($) {
var form = $('form'), oldSubmit = form[0].onsubmit;
form[0].onsubmit = null;
$('form').submit(function() {
// reset the onbeforeunload
window.onbeforeunload = null;
// run what actually was on
if(oldSubmit)
oldSubmit.call(this);
});
});
This is a tested code from my pages :)
This may not cover all of the postback situations, but you can tell if the page was posted back by an ASP control by interrogating the __EVENTTARGET hidden input.
This input is set by ASP when the page is posted back by an ASP control.
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
}
JavaScript runs on the client; as far as the client is concerned, a page does not maintain state from one view to the next. Postbacks are entirely an ASP.NET concept.
You can get around this by running some code on the server-side which defines a JavaScript variable based on whether or not Page.IsPostBack is true.
Example:
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page.IsPostBack -> client</title>
<script type="text/javascript">
var isPostback = <%= Page.IsPostBack %>;
console.log("IsPostBack: " + isPostback);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btnTest" Text="Click me..." />
</div>
</form>
</body>
</html>
Related
I got an ASPX page with the folowing code behind
public partial class test : Page
{
protected void test(object sender, EventArgs e)
{
throw new Exception("test");
}
}
And the following ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Thumbnail</title>
</head>
<body>
<form id="form1" runat="server">
<div id="buttonTarget">
</div>
</form>
</body>
</html>
If I run the following javascript a button is added to the page:
$('#buttonTarget').html('<asp:Button runat="server" ID="tst" CssClass="buttons" OnClick="Test" Text="Test"/>');
The buttons shows the same way as an asp tag shows in element inspector.
And when I click the button the server sided function is called and the site breaks with the "test" exception
I know this isn't good practice but I want to know why this works. Why does this button call the server sided function and why is it displayed as a normal button ?
--EDIT--
The aspx code was a simplified version. The actual code used a gridview control and used javascript to insert rows in the table. These rows hold the tags.
Expanding on what #Mamun was probably saying, when the page is executing on the server, it's seeing the asp tag in the JS string and translating it into the appropriate HTML. If you view source on your page in the browser, you'll probably see something like this instead of the ASP tag in your JS call:
$('#buttonTarget').html('<input type="submit" name="ctl00$MainContent$tst" value="Test" id="MainContent_tst" class="buttons" />');
Is there a way to configure in Chrome (or any browser) that whenever a webpage changes it automatically goes back to the previous page.
E.g. If a user presses a "Submit" button on a survey, they will be shown the "finish" message but then the original webpage with the survey will load again?
To go to previous page use
window.history.go(-1);
Example
<!DOCTYPE html>
<head>
<script>
function initialize(){
var submitBtn = document.getElementById("submitBtn");
submitBtn.addEventListener("click",function(){
alert("successfully submited");
setTimeout(goBack,2000)
});
function goBack(){
window.history.go(-1);
}
}
window.addEventListener("load",initialize);
</script>
</head>
<body>
<button id="submitBtn">Submit</button>
</body>
To go to a specific page
window.location = "";
While I'm not convinced it's a great idea, you know your requirements better than I do.
So to go back, you run this javascript.
window.history.back()
When you say immediately go back, I assume you want them to see the finish message first before being sent back after, say, 3 seconds?
<script>
setTimeout(function() {
window.history.back();
}, 3000);
</script>
Edit
If you want to redirect without javascript, you can use a meta tag in the header
<meta http-equiv="refresh" content="3; url=http://www.example.com" />
So if you use server side rendering you could reference the HTTP_REFERER header and inject it into your meta tag.
If you don't use server side rendering (PHP, MVC, React, etc) and you can't use javascript, then no; you're stuffed.
Am facing a very strange issue.
I've a hidden fields as shown below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="hid_test" ClientIDMode="Static" runat='server' />
</div>
</form>
<script language="javascript" type="text/javascript">
$(function () {
alert($('#hid_test').val());
});
</script>
</body>
</html>
And in server side am setting a value to the hidden field as follows
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
hid_test.Value = "abcd"
End If
End Sub
Very simple code. So in the first run the alert shows as "abcd" since am setting that from server side. OK.. Thats fine.
Then what I did was I changed hidden field value using jquery from console as below
$('#hid_test').val('12');
After this change does when I hit F5 (Page reloads) obviously my server side code hits and the hidden fields value should be changed to abcd
But when the page loads the alert says 12 itself. Means its keeping the value set from client side. Any kind help appreciated. Am testing in Firefox.
I disabled FF form fill feature as follows
Firefox auto-fills forms with previous values by default. If you turn off the feature, you should stop seeing that behavior. This question and its answers seem to suggest there's no simple way to tell Firefox not to do that in the HTML; instead, the answers there focus on using JavaScript on load/unload to set the field values (e.g., on load to overwrite what Firefox auto-filled; on unload to encourage Firefox to remember the values the page author wants remembered).
Add the autocomplete="off" tag.
I'm trying to get a server side button to do some stuff on the client side (id="formSrvBtn"), but for some reason the setInterval functionality does not work as expected (expression to evaluate is not evaluated), i've also tried using a client button instead of the server button (id="formCltBtn") which would also be a valid option but with the same unwanted result...
The only way to make it work is to put the button completely outside of the server side context (id="cltBtn") which is not a valid option in our real life scenario.
Heres is the html for a small aspx confirming all of the above:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type = "text/javascript">
function dumb_setInterval() {
setInterval(function(){alert('dumb setInterval after 5000ms!');}, 5000);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<p><asp:ImageButton id="formSrvBtn"
runat="server"
OnClientClick="dumb_setInterval();"
AlternateText="This server img button's setInterval does not work!"
>
</asp:ImageButton></p>
<p><button id="formCltBtn"
onclick="dumb_setInterval();"
>
This client button's setInterval does not work!
</button></p>
</form>
<p><button id="cltBtn"
onclick="dumb_setInterval();"
>
This client button's setInterval works!
</button></p>
</body>
</html>
Form (id="form1") needs to runat server in our real life scenario, so what i need is to get buttons (id="formSrvBtn" or id="formCltBtn") click event firing the setInterval correctly.
Here's the solution rep (for visual studio 2005, sorry...): https://github.com/RASMiranda/setIntervalRunAtServer
And here's the direct link to download the solution: https://github.com/RASMiranda/setIntervalRunAtServer/archive/master.zip
You need to ensure the default behaviour of OnClientClick on your ImageButton is not called, as this will force a postback. You can do this by returning false from your dumb_setInterval() method:
function dumb_setInterval() {
setInterval(function(){alert('dumb setInterval after 5000ms!');}, 5000);
return false;
}
Then adding a return statement to your attribute:
<asp:ImageButton id="formSrvBtn"
runat="server"
OnClientClick="return dumb_setInterval();"
I need to put some javascript absolutely in the <head> block of the page -- it must execute before the rest of the page because a possible outcome of the script is to redirect to a different page.
However, when I use RegisterClientScriptInclude (to put some jQuery in there) and RegisterClientScriptBlock for my code which uses the jQuery, it puts it near the top of the <body> block, and it does not execute. I can't see a way to programmatically put this javascript into the <head> block -- it must be programmatically because sometimes I don't want it there, and sometimes I do.
I've tried to see if I can directly reference Content1, the ID of the asp:Content element corresponding to the <head> block, but no go.
Just in case anyone thinks that RegisterStartupScript might work: it doesn't. It puts it lower in the <body> block than everything else. Oddly enough.
Want some code? Here:
Type csType = this.GetType();
ClientScriptManager clientScript = Page.ClientScript;
if (!clientScript.IsClientScriptIncludeRegistered(jqueryScriptName))
{
clientScript.RegisterClientScriptInclude(jqueryScriptName, "~/Scripts/jquery-1.7.1.min.js");
}
if (!clientScript.IsClientScriptBlockRegistered(citrixDetectorScriptName))
{
clientScript.RegisterClientScriptBlock(csType, citrixDetectorScriptName, citrixDetectorScriptText, true);
}
By popular demand, how I detect the ActiveX component. This is JScript.
try {
var icaObj = new ActiveXObject("Citrix.ICAClient");
var CitrixVersion = icaObj.ClientVersion.split(".");
var MajorMinorVersion = CitrixVersion[0] + "." + CitrixVersion[1];
if (MajorMinorVersion == "11.0") {
// Citrix is OK
}
else {
window.navigate("WrongCitrix.aspx?Citrix=" + MajorMinorVersion);
}
}
catch (e) {
window.navigate("NoCitrix.aspx");
}
If the ActiveX component is not present, then redirection is a page that tells the user they need to install it. If the ActiveX component is any other version than 11.0, then the redirect is to a page that explains this and how to deal with the situation (backrevving for example).
An prior check during page load checks to make sure they have Internet Explorer v4 thru v9, because any other version will not work with the product (and IE10+ will crash if it even tries to load v11.0 of the ActiveX component).
If I understand your question, you can insert PlaceHolder control wherever you want inside the page.
<%# Page Language="C#" AutoEventWireup="True"
CodeBehind="Default.aspx.cs" Inherits="WebApplicationTelerik.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl(
"<script type=\"text/javascript\"> alert('here'); </script>"));
}
document.GetElementsByTagName("head")[0].appendChild( newScriptNode );
or jQuery
$("head")[0].append( newScriptNode );
If you really must insert JavaScript into the head tag, you can just make it an ASP.NET control and insert a control into it's child collection.
E.g. In the ASPX file:
<head runat="server" id="header">...</head>
In the code behind:
header.Controls.Add(new Literal("<script type='text/javascript'>...</script>"));
Although I do think you need to think about your process, it would be more efficient to redirect the user in the back-end before the page is rendered.
Oh and RegisterStartupScript correctly places your JavaScript after your html for increased load performance.