Friday 1 July 2016

Query String Passing in Sharepoint Hosted App in Javascript



Pass Querystring value from SharePoint Page to App Part(Client web part)

As we know an App Part generates an Iframe when it is added into a SharePoint page, so we face difficulty to pass query string value from page to app part.
Here is the simple way to handle this. Using below information we can pass information from SharePoint page/webpart to our app part.
Step 1: 
In your App part go to element.xml file and add one dummy property which you only be using to pass Query string values. Keep Property name same as Query String Name as shown below:
AppProperty
Step 2: On your page where you have added App part, add a script editor or content editor web part just below the app part and add below script:
<script>
var arrFrames = document.getElementsByTagName(“iframe”);
for(i = 0; i< arrFrames.length; i++)
{
var iFrame=arrFrames[i];
var clientID=”QueryStringIDValue”;
if(iFrame.src.indexOf(clientID) != -1)
{
alert();
var queryStringValue=getQuerystring(‘QueryStringID’);
if(queryStringValue != null)
{
iFrame.src=iFrame.src.replace(clientID,queryStringValue);
}
}
}
function getQuerystring(key)
{
key = key.replace(/[\[]/,”\\\[“).replace(/[\]]/,”\\\]”);
var regex = new RegExp(“[\\?&]”+key+”=([^&#]*)”);
var qs = regex.exec(window.location.href);
if(qs == null)
return null;
else
return qs[1];
}
</script>
Above code will find out all the iframes and see where the QueryStringIDValue exists on scr of each Iframe as shown in below figure and replace with QueryString value of the page:
Here is the iframe generated by the app part from the page view source:
IframeViewPage
Our JavaScript will replace the property value with the query string value and the query string value can be used within app page load.

Get the Passed value into Our Page

Way of getting value:

 sponsorItemID = GetParameterValues("SponsorItemID");

Passing parameter to the function
 
function GetParameterValues(param) {
    var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 
    for (var i = 0; i < url.length; i++) {
        var urlparam = url[i].split('=');
        if (urlparam[0] == param) {
            return urlparam[1];
        }
    }
}
   

No comments:

Post a Comment