Question

I have a link like that. It's getting from instagram api.

http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b

How can I get this link from codebehind? I can take it with js but i can't get it after assign to label. I mean:

<script>
    function getURL(){
        document.getElementById('lblAccessToken').innerText = location.href;
    }
</script>

This js function is in body onload event. How can I reach this innerText value from codebehind?

Was it helpful?

Solution

If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this

Markup

<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var myToken = GetHashParameterByName("access_token");
        $("#lblAccessToken").html( myToken );
    });

    function GetHashParameterByName(name) {    
        var match = RegExp('[#&]' + name + '=([^&]*)')
                .exec(window.location.hash);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));    
    }
</script>

You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things

  1. Pass the hash value to a jQuery ajax method and store it there.
  2. Grab the hash value and redirect to the same page after converting it to a querystring

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var myToken = GetHashParameterByName("access_token") || "";
        if(my_token !=== ""){
            window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
        }
    });

    function GetHashParameterByName(name) {    
        var match = RegExp('[#&]' + name + '=([^&]*)')
                .exec(window.location.hash);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));    
    }
</script>

Now at Page_Load, grab it like

string token = Request.QueryString["access_token"];

Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top