retrieve value from javascript function in codebehind

18,846

Solution 1

You cannot directly call a client side javascript method from server side code . For that first you need to assign the function result to value of some hidden variable and then access it in server side

Suppose you have an hidden field like this

<input type="hidden" runat="server" id="hdnVal"/>

then you can set the value as below

document.getElementById("hdnVal").value=isIFrame();

then at serve side

 string resutOfExecuteJavaScript = hdnVal.Value;

Solution 2

using _doPostBack, you can solve this one

      <script type="text/javascript">
             function isIFrame() {
            var isInIFrame =(top.location != self.location);
            var result;
            if (isInIFrame) { 
                result="inside";
             }
           else
             {
             result ="outside";
             }
           __doPostBack('callPostBack', result);
        </script>
    </head>

In code behind section

protected void Page_Load(object sender, EventArgs e)
{
    this.ClientScript.GetPostBackEventReference(this, "arg");
    if (IsPostBack)
    {
        string eventTarget = this.Request["__EVENTTARGET"];
        string eventArgument = this.Request["__EVENTARGUMENT"];

        if (eventTarget != String.Empty && eventTarget == "callPostBack")
        {
            if (eventArgument == "inside"){   
               //do something
               }
           else if(eventArgument == "outside")
            {
           //do something
           }
       }
    else
    {
       // set the button click
        btnclick.Attributes.Add("onClick", "isIFrame();");
    }
}

Below link will help you out to get more idea.

http://www.dotnetcurry.com/ShowArticle.aspx?ID=203

Share:
18,846
Mo7ammed
Author by

Mo7ammed

Updated on June 29, 2022

Comments

  • Mo7ammed
    Mo7ammed almost 2 years

    How can I retrieve value from javascript function in codebehind, on page load .. javascript function like :

    <script type="text/javascript">
            function isIFrame() {
                var isInIFrame = (top.location != self.location);
                if (isInIFrame) {
                    return "inside";
                }
                else {
                    return "outside";
                }
            }
        </script>
    

    and code behind like :

    protected void Page_Load(object sender, EventArgs e)
        {
            string resutOfExecuteJavaScript = "";
            // resutOfExecuteJavaScript = isIFrame(); // from javascript
    
            if (resutOfExecuteJavaScript == "inside")
            {
                // do something
            }
            else
            {
                // do something
            }
        }
    

    thank you.