Thursday, November 13, 2014

Javascipt Redirect Fails within SharePoint web part (window.location.href, document.location.href not working)

The Problem

When you create a web part within SharePoint, whether its a Content Editor Web Part or a Data Form Web Part, you may wish to include a button that has a redirect action.  This redirect action could be static or dynamic, they key is that you wish to use something like:

function goToLink()
    if (possible code that determines which link to use...)
        window.location.href = '/SitePages/MyPage.aspx';

<button  class="dashboard-button" onclick="goToLink();">Go To Link </button>

This very simple example looks like it should work every time, and if it is done outside of SharePoint on its own web page, it does.

If however you embed this code within a SharePoint web part, it will sometimes  work.  Some users will be able to click the button and have it redirect the first time.  Some users will have to click the button multiple times, each time resulting in a page refresh, before the button works.  This type of intermittent issue can also be very challenging to troubleshoot.

The Solution

Fortunately, this one is a really simple solution.  Simply add the button type to your button markup:

<button type="button" class="dashboard-button" onclick="goToLink();">Go To Link</button>

By default, SharePoint sets the button type as "submit", which has the action of submitting the entire page, rather than just your javascript.  If you look at the source code behind a web page in SharePoint, you will typically see a line like this:
<form method="post" action="HomePage.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm">

If your button is not defined as a button type, then it submits the entire form, including running the onsubmit event shown above. This may result in SharePoint javascript conflicts with the window.location object, where the window.location object is overwritten locally by SharePoint before your javascript redirect fires, effectively refreshing the page instead of redirecting.  By setting the type to button, just the javascript you created fires, without the unwanted conflicts with other page events accessing the same object.

No comments:

Post a Comment