Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, 20 May 2014

Click Jacking

Clickjacking (also known as user-interface or UI redressing and IFRAME overlay) is an exploit in which malicious coding is hidden beneath apparently legitimate buttons or other clickable content on a website.
Ex: A visitor to a site thinks he is clicking on a button to close a window; instead, the action of clicking the “X” button prompts the computer to download a Trojan Horse, transfer money from a bank account or turn on the computer’s built-in microphone. The host website may be a legitimate site that's been hacked or a spoofed version of some well-known site. The attacker tricks users into visiting the site through links online or in email messages.
Suppose I am using iframe in your for some reason. I want to give security so that no one can hack using click jacking technique by loading his content instead of mine.
Suppose in design I am using iframe and id of iframe is ifShowThen just copy paste below code to prevent click jack on the site.

<script type="text/javascript" language="Javascript">
        function Check() {           
            try{
                if (window.top !== window.self) {
                    window.top.location = window.self.location;
                    return;
                }

                if (window.top.location.host != window.self.location.host) {
                    //window.top.location = window.self.location;
                    window.top.location = window.self.location;
                    return;
                }               
                var domain = document.getElementById('ifShow').src.replace('http://', '').replace('https://', '').split(/[/?#]/)[0];
                if (window.self.location.host != domain) {
                    window.top.location = window.self.location;
                    return;
                }
            }
            catch (ex)
            { window.top.location = window.self.location; /* everyone else */ }
           
        }
        setInterval(Check, 1000);
        Check();

    </script>

Wednesday, 27 February 2013

Disable mouse right click using javascript


When we right click on the page and click on the view source option then page html source along with inline css will see. From the source code, they can figure out how you did things and where your graphics are stored, or just plain old copy your content coding. To prevent the user to know the source detail we disable right click on the page.

<script type="text/javascript">
        var message = "Right Click Disabled!";
        function DisableIE() {
            if (event.button == 2) { alert(message); return false; }
        }
        function DisableOther(e) {
            if (document.layers || document.getElementById && !document.all)
            { if (e.which == 2 || e.which == 3) { alert(message); return false; } }
        }
        if (document.layers) { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = DisableOther; }
        else if (document.all && !document.getElementById) { document.onmousedown = DisableIE; }
        document.oncontextmenu = new Function("alert(message);return false")
</script>

Disable F12 key in the browser


When user press F12 key, browsers developer tool bar will open in the below portion of the browser. By
using the developer tool bar user can see the design, javascript code and corresponding css applied to the controls in the page. To prevent the user to do that we will the hide developer tool bar.

You can use the below code to do that. Write the below code in the head section of the page.
<script type="text/javascript">

document.onkeydown = function (event)
{
     event = (event || window.event);
     if (event.keyCode == 123 || event.keyCode == 18)
     {
           alert("This function is disabled here");
           return false;
     }
}
</script>

Friday, 12 October 2012

Add to Bookmark Link using JS


<script language="javascript" type="text/javascript">
function addBookmark()
{
    bookmarkurl = document.URL;
    bookmarktitle = document.title;
    if (document.all)  //Check the condition for IE
        window.external.AddFavorite(bookmarkurl, bookmarktitle)
    else if (window.sidebar) // Check the condition for Mozilla
   {
       window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
   }
}
</script>

<a href="javascript:addBookmark();">Bookmark this page!</a>

Sunday, 15 April 2012

Credit Card Number validation using JS


// Card Number = Credit Card number
// Card name = Card Type

function checkCreditCard (cardnumber, cardname) {
   
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types as follows.
 
  //  Name:         As in the selection box of the form - must be same as user's
  //  Length:       List of possible valid lengths of the card number for the card
  //  prefixes:     List of possible prefixes for the card
  //  checkdigit:   Boolean to say whether there is a check digit
 
  cards [0] = {name: "Visa",
               length: "13,16",
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard",
               length: "16",
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub",
               length: "14,16",
               prefixes: "305,36,38,54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche",
               length: "14",
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx",
               length: "15",
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover",
               length: "16",
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB",
               length: "16",
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute",
               length: "15",
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo",
               length: "16,18,19",
               prefixes: "6334,6767",
               checkdigit: true};
  cards [9] = {name: "Switch",
               length: "16,18,19",
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro",
               length: "12,13,14,15,16,18,19",
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron",
               length: "16",
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard",
               length: "16,17,18,19",
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
             
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
 
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false;
  }
 
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false;
  }
   
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
 
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false;
  }
     
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
 
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
   
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
   
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
   
      // Add the units element to the checksum total
      checksum = checksum + calc;
   
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    }
 
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false;
    }
  }

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false;
  var undefined;

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
   
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
     
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
     
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false;
  }
   
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
 
  // See if all is OK by seeing if the length was valid. We only check the length if all else was
  // hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false;
  };  
 
  // The credit card is in the required format.
  return true;
}

How to trim the space using JS


function Trim(str)
{
    while (str.substring(0,1) == ' ') // check for white spaces from beginning
    {
        str = str.substring(1, str.length);
    }
    while (str.substring(str.length-1, str.length) == ' ') // check white space from end
    {
        str = str.substring(0,str.length-1);
    }
    return str;
}

Sunday, 4 March 2012

Disable back button using JS

Create 2 page.

In asp1.aspx :
 <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/ asp2.aspx " />

In asp2.aspx:
In the body section
hi

<script language="javascript" type="text/javascript">
function DisableBackButton() {
window.history.forward();
}
setTimeout("DisableBackButton()", 0);

</script>





Wednesday, 29 February 2012

Phone number validation using JS


if (txtPhone.value == '')
{
   alert("Please enter phone number.");
   txtPhone.focus();
   txtPhone.value='';
   txtPhone.style.border = '1px solid red';
   return false;
}
else if (txtPhone.value != "")
{
   var targ=txtPhone.value.replace(/[^\d]/g,''); // remove all non-digits
   if(!targ || isNaN(targ) || targ.length!=10)
    {
        alert("Invalid Phone number.");
        txtPhone.value = "";
        txtPhone.style.border = '1px solid red';
        txtPhone.focus();
        return false;
    }
}

Wednesday, 11 January 2012

Call Server Side Function From Javascript


In design :
In the head section:

 <script type="text/javascript" language="javascript">
    function callme(chkCall)
    {
       var chkCall=document.getElementById(chkCall);
       if(chkCall.checked==true)
        {
             chkCall.checked=true;
             PageMethods.GetContactName();
        }
        else
        {
              chkCall.checked=false;
        }
    }
    </script>

In the body section:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
<asp:CheckBox ID="chkCall" runat="server" />

In the CS part :

protected void Page_Load(object sender, EventArgs e)
    {
        chkCall.Attributes.Add("onclick", "javascript:callme('" + chkCall.ClientID + "')");
    }

    [System.Web.Services.WebMethod]
    public static void GetContactName()
    {
        Response.Write("your name");
    }

Monday, 2 January 2012

Resize the TextBox dynamically according to text


<script type="text/javascript">
function setHeight(txtNote) {
txtNote.style.height = txtNote.scrollHeight + "px";
}
</script>

In the body :
<asp:TextBox ID="txtNote" runat= "server" TextMode="MultiLine"  onkeyup="setHeight(this);" onkeydown="setHeight(this);" />

Add to Bookmark using JS


<script language="javascript" type="text/javascript">
function addBookmark() {
bookmarkurl = document.URL;
bookmarktitle = document.title;
if (document.all)  //Check the condition for IE
window.external.AddFavorite(bookmarkurl, bookmarktitle)
else if (window.sidebar) // Check the condition for Mozilla
{
window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
}
}
</script>

In the body part :
<a href="javascript:addBookmark();">Bookmark this page!</a>

Saturday, 24 December 2011

Check Floating point value using JS


<asp:TextBox ID="txtYearValue" runat="server" onkeyup=" isNFloat (event)"></asp:TextBox>

function isNFloat(e)
{
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
var keyCode = (isNN) ? e.which : e.keyCode;
//alert(keyCode);
if (isNN)
{
if (keyCode == 0)
return true;
}
if((keyCode>47&&keyCode<58)||(keyCode==8)||(keyCode==9)||(keyCode==110)||(keyCode==46))
{
return true;
}
else
{
if (e.returnValue)
{
e.returnValue = false;
return false;
}
else if (e.preventDefault)
{
e.preventDefault();
return false;
}
this.event.returnValue = false;
return false;          
}
}

Saturday, 17 December 2011

Check DateTime format using JS


The below function checks date in mm-dd-yyyy format.


<asp:TextBox ID="txtYearValue" runat="server" onBlur="checkdate(this)"></asp:TextBox>

function checkdate(input)
{
var validformat=/^\d{2}\-\d{2}\-\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("-")[0]
var dayfield=input.value.split("-")[1]
var yearfield=input.value.split("-")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false)
      input.select()
return returnval
}

Friday, 28 October 2011

Remove Item from Drop Down List using JS


<script type="text/javascript">
function removeListItem()
{
      var htmlSelect=document.getElementById('selectYear');
      if(htmlSelect.options.length==0)
     {
           alert('You have removed all options');
            return false;
      }
      var optionToRemove=htmlSelect.options.selectedIndex;
      htmlSelect.remove(optionToRemove);
      alert('The selected option haas been removed successfully');
      return true;
}


<asp:DropDownList ID="selectYear" runat="server">
<asp:ListItem Value="2000">2000</asp:ListItem>
<asp:ListItem Value="2001">2001</asp:ListItem>
<asp:ListItem Value="2002">2002</asp:ListItem>
<asp:ListItem Value="2003">2003</asp:ListItem>
<asp:ListItem Value="2004">2004</asp:ListItem>

</asp:DropDownList>

<input name="btnRemoveItem" type="button" id="btnRemoveItem" value="Remove Option" onClick="javascript:removeListItem();" />


Add value to the Drop Down List using JS


function addNewListItem()
{
     var htmlSelect = document.getElementById('selectYear');
     var optionValue = document.getElementById('txtYearValue');
     var optionDisplaytext = document.getElementById('txtYearDisplayValue');
     if (optionValue.value == '' || isNaN(optionValue.value))
    {
          alert('please enter option value');
           optionValue.focus();
           return false;
    }
    if (optionDisplaytext.value == '' || isNaN(optionDisplaytext.value))
   {
          alert('please enter option display text');
          optionDisplaytext.focus();
          return false;
   }
    if (isOptionAlreadyExist(htmlSelect, optionValue.value))
   {
          alert('Option value already exists');
          optionValue.focus();
          return false;
    }
    if (isOptionAlreadyExist(htmlSelect, optionDisplaytext.value))
    {
          alert('Display text already exists');
          optionDisplaytext.focus();
          return false;
     }
      var selectBoxOption = document.createElement("option");
      selectBoxOption.value = optionValue.value;
      selectBoxOption.text = optionDisplaytext.value;
       htmlSelect.options.add(selectBoxOption);
      alert("Option has been added successfully");
      return true;
}

function isOptionAlreadyExist(listBox, value)
 {
       for (var x = 0; x < listBox.options.length; x++)
      {
                if (listBox.options[x].value == value || listBox.options[x].text == value)
                {
                       return true;
                }
       }
       return false;
}

</script>

<asp:DropDownList ID="selectYear" runat="server">
    <asp:ListItem Value="2000">2000</asp:ListItem>
    <asp:ListItem Value="2001">2001</asp:ListItem>
    <asp:ListItem Value="2002">2002</asp:ListItem>
    <asp:ListItem Value="2003">2003</asp:ListItem>
    <asp:ListItem Value="2004">2004</asp:ListItem>
</asp:DropDownList>

Option Value
<asp:TextBox ID="txtYearValue" runat="server"></asp:TextBox>
Option Display Text
<asp:TextBox ID="txtYearDisplayValue" runat="server"></asp:TextBox>
<input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javascript:addNewListItem();" />

Monday, 24 October 2011

Select and Deselect Checkbox with in gridview using Javascript


<asp:GridView ID="gdvShowData" runat="server" AutoGenerateColumns="False" CssClass="gdvBody" Width="100%" >
<Columns>
   <asp:TemplateField>
       <HeaderTemplate>
               <asp:CheckBox ID="chkheader" runat="server"  onclick="Calculate(this);" ToolTip="Check to select all rows"/>
       </HeaderTemplate>
       <ItemTemplate>
               <asp:CheckBox ID="chkchild" runat="server" />
       </ItemTemplate>
   <ItemStyle Width="8%" />
</asp:TemplateField>        
    <asp:BoundField HeaderText="Name" DataField="Name" />            
 </Columns>
 <EmptyDataTemplate>
    There is no record.
 </EmptyDataTemplate>
</asp:GridView>


function Calculate(SelectAllCheckBox)
{
        var chkAll=document.getElementById(SelectAllCheckBox.id);
        var Parentgrid = document.getElementById('<%= gdvShowData.ClientID %>');      
        var items = Parentgrid.getElementsByTagName('input');
        for (i = 1; i < items.length; i++)
        {          
            if (items[i].type == "checkbox")
            {              
                if (chkAll)
                 items[i].checked = chkAll.checked;              
            }
        }
}

function Selectchildcheckboxes(header)
{
    var ck = header;
    var count = 0;
    var gvcheck = document.getElementById('gdvShowData');
    var headerchk = document.getElementById(header);
    var rowcount = gvcheck.rows.length;
    for (i = 1; i < gvcheck.rows.length; i++)
   {
       var inputs = gvcheck.rows[i].getElementsByTagName('input');
       if (inputs[0].checked)
      {
            count++;
       }
    }
     if (count == rowcount-1)
    {
           headerchk.checked = true;
     }
    else
    {
           headerchk.checked = false;
     }
}

protected void gdvShowData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox headerchk = (CheckBox)gdvShowData.HeaderRow.FindControl("chkheader");
CheckBox childchk = (CheckBox)e.Row.FindControl("chkchild");
childchk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + headerchk.ClientID + "')");
}
}


Tuesday, 18 October 2011

How to compare DateTime

function Datevalidate(txtFromdate,txtToDate)
{

   var txtFromdate = document.getElementById(txtFromdate);
   var txtToDate = document.getElementById(txtToDate);

   if(txtFromdate.value!="" || txtToDate.value!="")
  {
        var str1 = txtFromdate.value;
        var str2 = txtToDate.value;
        var dt1  = parseInt(str1.substring(0,2),10);
        var mon1 = parseInt(str1.substring(3,5),10);
        var yr1  = parseInt(str1.substring(6,10),10);
        var dt2  = parseInt(str2.substring(0,2),10);
        var mon2 = parseInt(str2.substring(3,5),10);
        var yr2  = parseInt(str2.substring(6,10),10);
        var date1 = new Date(yr1, mon1, dt1);
        var date2 = new Date(yr2, mon2, dt2);     
        if(date2 < date1)
        {
            alert("To Date cannot be lesser than From Date");
            return false;
        }  
    }
}

Monday, 10 October 2011

Enable disable button on checkbox check


function hideOnCheck()
{
   var chk = document.getElementById('<%=chk.ClientID%>');
   var btn = document.getElementById('<%=btnSubmit.ClientID%>');
   if (chk && btn)
   {
      if (chk.checked == true)
      {
         btn.disabled = false;
      }
      else
      {
         btn.disabled = true;
      }
    }
}

<asp:CheckBox ID="chk" runat="server" Text="All the above data are correct" onclick="hideOnCheck();"/>

Hide row by selecting radio button option


function setRowonClick()
{
    var rowOther = document.getElementById('<%=trShowDetail.ClientID%>');
    if (rowOther)
   {
        var s = document.getElementById('<%=rbtnIsPS.ClientID%>');
        var s1 = s.getElementsByTagName('input');
        for (var i = 0; i < s1.length; i++)
       {
            if (s1[i].checked)
           {
                  if (s1[i].checked && s1[i].value == '0')
                 {
                      rowOther.style.display = '';
                 }
                 else
                 {
                     rowOther.style.display = 'none';
                 }
             }
          }
     }
}

<asp:RadioButtonList ID="rbtnIsPS" runat="server" RepeatDirection="Horizontal" onclick="setRowonClick();">

Dropdownlist validate


function OnSelectedIndexChange()
{
   var s = document.getElementById('<%=ddlPosition.ClientID%>');
   if (s.value == '0')     // or  if (s.options[s.selectedIndex].text=='select')
   {
      alert("Please select the different option.");
      return false;
   }
   else
      return true;
}

<asp:DropDownList ID="ddlPosition" runat="server" onchange="OnSelectedIndexChange();"/>