Working with links in a Client Web Part with SharePoint 2013

If you've followed Building a SharePoint-hosted Client Web Part in SharePoint 2013, you have a good start on working with Client Web Parts with the new SharePoint 2013 app model. In an app part, everything you do is inside an IFRAME. You need to remember this whenever you create links inside your App Part. This provides a small level of complexity but it's not that bad when you think about it. Let's start by taking a look at what it will take to link to the default page of the app. Typically this page is called default.aspx and is hosted at a URL like the one below.


Effectively this url, has a prefix (app), an Id, a subdomain hosting the apps, the current site I am running it on (developer site), followed by the app name and finally the Pages folder (which matches the name I have in Visual Studio). The .aspx page hosting your Client Web Part also typically sits in this folder as well. In my case it's called HelloWorldClientWebPart.aspx. That means, if I want to create a link in my Client Web part to the app's default page, I should be able to do so with a relative link like this:

<a href="default.aspx">Go to app default page</a>

This will get me to the page, but unfortunately here is the result:


The link works but that page is designed to run in the full browser so it doesn't have the AllowFraming tag. Fixing this is simple though. Just add target="_top" to have the link navigate the parent frame instead of the IFRAME. The link now looks like this:

<a href="default.aspx" target="_top">Go to app page 2</a>

Now the link will work.

Another common scenario you might run into is linking to a related list. In this case, I have a list called TestList with a relative URL of Lists/TestList. We can get to this, but we need to use a relative path and go up one folder first since the page executes out of the Pages library. Here is what that link would look like.

<a href="../Lists/TestList" target="_top">Go to list</a>

Lastly, there may be a time when you want to retrieve the URL to the app web from the client web part. You can do this with some CSOM. Start by getting a reference to the app web.

var context;

var web;

context = new SP.ClientContext.get_current();

web = context.get_web();

You then need to load the context for the web object and then execute a query.


context.executeQueryAsync(onUrlRequestSucceeded, onQueryFailed);

On the success method, you can read the URL. I then get a reference to the link on the page I want to update and assign the href attribute.

function onUrlRequestSucceeded() {

var appWebUrl = web.get_url();

$("#MyLink").attr("href", appWebUrl);


This gives you some options for working with links. It's not entirely complicated, but I thought it was worth a quick write-up.