Thursday, July 6, 2017

Getting URL query parameters when working in the SharePoint Framework

Image result for upper lower case p

Fetching values from the query string of the URL is something developers are constantly doing, as in this sample URL where I have two parameters, mvp and status.

https://madcow.sharepoint.com/?mvp=mikael&status=awesome

What you can use is the URL object in JavaScript which is still in a proposed spec.

The URL object is not fully supported by all browsers yet (looking at you Microsoft), but fortunately SPFx provides a polyfill for the URL object so it will work fine in IE10 as well.

There is however a small issue. Currently SPFx uses TypeScript v2.2.2, which access the query parameters with searchparams (lowercase p) instead of searchParams (uppercase p). This means that to avoid an error in VSCode or when building you need to use the lowercase p version – but this breaks in browsers which expect the uppercase p version *sigh*.

TypeScript v2.3.4, for example, support the uppercase p version just fine. So until SPFx bumps the TypeScript version to something supporting the uppercase p version, a workaround is to use the any keyword in TypeScript at the cost of loosing intellisense, but it works.

const url : any = new URL(window.location.href);
const mvp = url.searchParams.get("mvp");
const awesome = url.searchParams.get("awesome");

This way you won’t get errors when building your SPFx solution, nor in any browsers. Happy query parametering – or write your own parser (or as Waldek Mastykarz said when chatting on this, use left-pad :)

No comments:

Post a Comment