Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My requirement: A message has to be prompted when user tries to close the browser windows

Whats Happening now: I have partially achieved my requirement. It prompts me a window to alert the user when he tries to close the browser

Problem what I am facing now: The alert message comes for every hyperlink in my page. Need help to fix this My asp.net (Content page) has only Gridveiw I am pasting the code below

Javascript which I am using now to close the window is

JavaScript
<script type="text/javascript" language="javascript">

     window.onbeforeunload = confirmExit;
     function confirmExit() {
         return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
     }


My asp.net content page contents

ASP.NET
<%@ Page Title="" Language="C#" MasterPageFile="~/Master/Menu.master" AutoEventWireup="true"
    CodeFile="TestScriptComponentPages.aspx.cs" Inherits="TestScriptComponentPages" %>

<%@ MasterType VirtualPath="~/Master/Menu.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">



<script src="JQueryScripts/jquery.js" type="text/javascript"></script>
<script src="JQueryScripts/colResizable-1.3.min.js" type="text/javascript"></script>
<script src="JQueryScripts/jquery.cookie.js" type="text/javascript"></script>
 <script type="text/javascript" language="javascript">

     window.onbeforeunload = confirmExit;
     function confirmExit() {
         return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
     }
     

  
     $(document).ready(function () {
         if ($.cookie('colWidth') != null) {
             var columns = $.cookie('colWidth').split(',');
             var i = 0;
             $('.GridViewStyle th').each(function () {
                 $(this).width(columns[i++]);
             });
         }

         $(".GridViewStyle").colResizable({
             liveDrag: true,
             gripInnerHtml: "<div class='grip'></div>",
             draggingClass: "dragging",
             onResize: onSampleResized
         });

     });

     var onSampleResized = function (e) {
         var columns = $(e.currentTarget).find("th");
         var msg = "";
         columns.each(function () { msg += $(this).width() + ","; })
         $.cookie("colWidth", msg);
     }; 
</script> 
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="overflow: scroll; height: 573px; width: 1030px">
        <%-- <asp:DataGrid ID="Grid" runat="server"   DataKeyField="ObjectName"

AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" 
        OnPageIndexChanged="Grid_PageIndexChanged" OnCancelCommand="Grid_CancelCommand"

OnDeleteCommand="Grid_DeleteCommand" OnEditCommand="Grid_EditCommand" 
        OnUpdateCommand="Grid_UpdateCommand" Height="287px" Width="416px">

<Columns>

<asp:BoundColumn HeaderText="TestWindow/Frame Name" DataField="BrowserPage">

</asp:BoundColumn>

<asp:BoundColumn HeaderText="Test Object" DataField="ObjectName">

</asp:BoundColumn>

<asp:BoundColumn HeaderText="Test Operation" DataField="Action">

</asp:BoundColumn>

<asp:BoundColumn  HeaderText="Test Data" DataField="TestData">

</asp:BoundColumn>
<asp:BoundColumn  HeaderText="ReUseableOutputData" DataField="ReUsableOutputData">

</asp:BoundColumn>
<asp:BoundColumn  HeaderText="Step Description" DataField="Steps">

</asp:BoundColumn>


</Columns>

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />

<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" Mode="NumericPages" />

<AlternatingItemStyle BackColor="White" />

<ItemStyle BackColor="#FFFBD6" ForeColor="#333333" />

<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

</asp:DataGrid>--%>
        <table>
            <tr>
                <td>
                    <asp:ImageButton ID="btnAdd" runat="server" ImageUrl="images/add.ico" CausesValidation="false"
                        OnClick="btnAdd_Click" />
                </td>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
        <asp:GridView ID="gvTestScriptComponent" runat="Server" CssClass="GridViewStyle" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="Black" DataKeyNames="ComponentID"
            ShowFooter="true" Height="110px" Style="margin-right: 0px" Width="990px" BackColor="White"
            OnRowDataBound="gvTestScriptComponent_RowDataBound" AutoGenerateEditButton="True"
            OnRowEditing="gvTestScriptComponent_RowEditing" OnRowCancelingEdit="gvTestScriptComponent_RowCancelingEdit"
            OnRowUpdating="gvTestScriptComponent_RowUpdating" OnRowDeleted="gvTestScriptComponent_RowDeleted"
            BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" 
            OnRowCommand="gvTestScriptComponent_RowCommand">
            <Columns>
                <asp:TemplateField HeaderText="ComponentID" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblComponentID" runat="server" Height="20px" Text='<%#Eval("ComponentID")%>'>  </asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Options" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:ImageButton ID="btnDelete" runat="server" ImageUrl="images/delete.ico" CausesValidation="false"
                            CommandName="DeleteRow" OnClick="btnDelete_Click" />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:ImageButton ID="btnSave" runat="server" ImageUrl="images/save.ico" CausesValidation="false"
                            CommandName="SaveRow" OnClick="btnSave_Click" />
                    </FooterTemplate>
                    <ItemStyle HorizontalAlign="Center"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="TestWindow/Frame Name" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblTestWindow" runat="server" Height="20px" Text='<%#Eval("BrowserPage")%>'>  </asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left"></ItemStyle>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlTestWindow" runat="server" Visible="true" AutoPostBack="True"
                            OnSelectedIndexChanged="ddlTestWindow_SelectedIndexChanged">
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlFooterTestWindow" runat="server" Visible="true" AutoPostBack="True"
                            OnSelectedIndexChanged="ddlFooterTestWindow_SelectedIndexChanged">
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Test Object" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblTestObject" runat="server" Height="20px" Text='<%#Eval("ObjectName")%>'>  </asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left"></ItemStyle>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlTestObject" runat="server" Visible="true" AutoPostBack="True"
                            OnSelectedIndexChanged="ddlTestObject_SelectedIndexChanged" >
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlFooterTestObject" runat="server" Visible="true" AutoPostBack="True"
                            OnSelectedIndexChanged="ddlFooterTestObject_SelectedIndexChanged">
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Test Operation" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblTestOperation" runat="server" Height="20px" Text='<%#Eval("Action")%>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left"></ItemStyle>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlTestOperation" runat="server" Visible="true">
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlFooterTestOperation" runat="server" Visible="true">
                        </asp:DropDownList>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Test Data" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblTestData" runat="server" Height="20px" Text='<%#Eval("TestData")%>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left"></ItemStyle>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtTestData" runat="server" Text='<%# Bind("TestData") %>' Visible="true">
                        </asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtFooterTestData" runat="server" Visible="true"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ReUseableOutputData" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblReUseableOutputData" runat="server" Height="20px" Text='<%#Eval("ReUsableOutputData")%>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left"></ItemStyle>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtReUseableOutputData" runat="server" Text='<%# Bind("ReUsableOutputData") %>'
                            Visible="true">
                        </asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtFooterReUseableOutputData" runat="server" Visible="true"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Step Description" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:Label ID="lblStepDescription" runat="server" Height="20px" Text='<%#Eval("Steps")%>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Left"></ItemStyle>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtStepDescription" runat="server" Text='<%# Bind("Steps") %>' Visible="true">
                        </asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtFooterStepDescription" runat="server" Visible="true"></asp:TextBox>
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" HorizontalAlign="Justify"
                VerticalAlign="Middle" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#4B4B4B" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#242121" />
            <EmptyDataTemplate>
                <table>
                    <tr style="background-color: #999999;">
                        <th>
                            Option
                        </th>
                        <th>
                            Test Window
                        </th>
                        <th>
                            Test Object
                        </th>
                        <th>
                            Test Operation
                        </th>
                        <th>
                            Test Data
                        </th>
                        <th>
                            ReUseableOutputData
                        </th>
                        <th>
                            StepDescription
                        </th>
                    </tr>
                    <tr>
                        <td headers="Option">
                            <asp:ImageButton ID="btnSave" runat="server" ImageUrl="images/save.ico" CausesValidation="false"
                                CommandName="FirstSaveRow" OnClick="btnSave_Click" />
                        </td>
                        <td headers="Test Window">
                            <asp:DropDownList ID="ddlFooterTestWindow" runat="server" Visible="true" AutoPostBack="True"
                                OnSelectedIndexChanged="ddlFooterTestWindow_SelectedIndexChanged">
                            </asp:DropDownList>
                        </td>
                        <td headers="Test Object">
                            <asp:DropDownList ID="ddlFooterTestObject" runat="server" Visible="true" AutoPostBack="True"
                                OnSelectedIndexChanged="ddlFooterTestObject_SelectedIndexChanged">
                            </asp:DropDownList>
                        </td>
                        <td headers="Test Operation">
                            <asp:DropDownList ID="ddlFooterTestOperation" runat="server" Visible="true">
                            </asp:DropDownList>
                        </td>
                        <td headers="Test Data">
                            <asp:TextBox ID="txtFooterTestData" runat="server" Visible="true"></asp:TextBox>
                        </td>
                        <td headers="ReUseableOutputData">
                            <asp:TextBox ID="txtFooterReUseableOutputData" runat="server" Visible="true"></asp:TextBox>
                        </td>
                        <td headers="StepDescription">
                            <asp:TextBox ID="txtFooterStepDescription" runat="server" Visible="true"></asp:TextBox>
                        </td>
                    </tr>
                </table>
            </EmptyDataTemplate>
        </asp:GridView>
        <table>
            <tr>
                <td>
                    <asp:ImageButton ID="btnAdd1" runat="server" ImageUrl="images/add.ico" CausesValidation="false"
                        OnClick="btnAdd_Click" />
                </td>
            </tr>
        </table>
    </div>
</asp:Content>
Posted
Comments
JoCodes 19-Dec-13 23:02pm    
Can you point out the issue exactly? Is the alert triggered on hyperlink clicks too?
JoCodes 19-Dec-13 23:04pm    
Let me know if you have an onUnload function too?
ShaHam11 19-Dec-13 23:47pm    
Yes I have Hyperlink(i.e update and cancel) and image button for (delete icon image) in my gridveiw.. So if click on this hyperlinks and buttons , the alert is triggred

Its because onbeforeunload event triggers not only when window closes but for hyperlink, document write/close actions etc. So need to exclude for such actions .

Try something like

C#
jQuery(
  function($)
  {     
    $(window).data('beforeunload',window.onbeforeunload);
      
    $('a[href^="javascript:"]')//detach and reassign on hyperlink hover
      .hover(
             function(){window.onbeforeunload=null;},
             function(){window.onbeforeunload=$(window).data('beforeunload');}
            );

  }
);


Or even
C#
document.getElementById('hyperlinkid').onclick = function () {
    window.onbeforeunload = null;
};


Hope this helps you...
 
Share this answer
 
v2
JavaScript
window.onbeforeunload = function (event) {
        var msg = 'You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?';

        if (((window.event.clientX || event.clientX) < 0) || ((window.event.clientY || event.clientY) < 0)) // [X] button
        {
            event = window.event;
            event.returnValue = msg;
            return msg;

        }
        if ((window.event.clientX < 0) || (window.event.clientY < 0)) // [X] button
        {
            event = window.event;
            event.returnValue = msg;
            return msg;

        }
        else if (window.event.altKey == true || window.event.ctrlKey == true) // ALT + F4
        {
            event = window.event;
            event.returnValue = msg;
            return msg;
        }
        else {

        }

    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900