Thursday, 14 August 2014

Pass Query string value from SharePoint Page to App Part

Steps:
1.Add Client web part to app part
2.Open  element.xml and add one Property
3.In the same element.xml file under Content you will find src, add your Property name
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<ClientWebPart Name="myApp" Title="myApp" Description="myApp Description" DefaultWidth="100" DefaultHeight="200">
<!-- Content element identifies the location of the page that will render inside the client web part
Properties are referenced on the query string using the pattern _propertyName_
Example: Src="~appWebUrl/Pages/ClientWebPart1.aspx?Property1=_property1_" -->
<Content Type="html" Src="~appWebUrl/?{StandardTokens}&amp;myQuryString=_myQuryString_" />
<!-- Define properties in the Properties element.
Remember to put Property Name on the Src attribute of the Content element above. -->
<Properties>
<Property Name="myQuryString" Type="string"
DefaultValue="myQuryStringValue"
RequiresDesignerPermission="true"
WebCategory="My First App"
WebDisplayName="My First App">
</Property>
</Properties>
</ClientWebPart>
</Elements>
view raw gistfile1.html hosted with ❤ by GitHub

4.Go to host web where you are having query string
5.Add App part
6.Add one script editor web part. It should be below to App.
7.In the script editor web part, read query string and write some js code to read iframes and replace your PropertyValue with query string value.(Since we updated Content src with Property in element.xml, that Property will be available in iframe of app part).
<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<script>
var arrAppIFrames = document.getElementsByTagName("iframe");
for(i = 0; i< arrAppIFrames.length; i++)
{
var currentiFrame=arrAppIFrames[i];
var propertValue="myQuryStringValue";
if(currentiFrame.src.indexOf(propertValue) != -1)
{
var queryStringValue = GetUrlKeyValue('ID', false, window.location.href);
if(queryStringValue != null)
{
currentiFrame.src=currentiFrame.src.replace(propertValue,queryStringValue);
}
}
}
</script>
view raw gistfile1.html hosted with ❤ by GitHub

8.Now in the App landing page load read the iframe code(Your query string value will be there with property="123" in the iframe). You can try with document.referrer and find your Property.
Use this value across the App.
var queryStirngValue = document.referrer.split("myQuryString")[1].split("%")[1].split("253D")[1];
view raw gistfile1.js hosted with ❤ by GitHub