|
| 1 | +--- |
| 2 | +title: Intercepting Query String Changes in Web Parts |
| 3 | +description: Building web parts that respond to query string changes. |
| 4 | +ms.author: bekaise |
| 5 | +ms.date: 01/28/2020 |
| 6 | +ms.prod: sharepoint |
| 7 | +localization_priority: Normal |
| 8 | +--- |
| 9 | + |
| 10 | +# Intercepting Query String Changes in Web Parts |
| 11 | + |
| 12 | +When building a web part that needs to take into account query string changes you can use the web API `window.___location.search` to read the query string. However if the user proceeds to click a link on the page that contains the same path as the current URL and only the query string changes, the URL in the address bar will be updated but the page will not re-render (due to performance reasons). This document is aimed at showing how you can take advantage of other web APIs to track query string changes and respond to them in your web part. |
| 13 | + |
| 14 | +First let's assume you have a basic webpart class that renders the current query string. |
| 15 | + |
| 16 | +```typescript |
| 17 | +export default class HelloWorldWebPart extends BaseClientSideWebPart<IHelloWorldWebPartProps> { |
| 18 | + public render(): void { |
| 19 | + this.domElement.innerHTML = window.___location.query; |
| 20 | + } |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +We can use the following changes to trigger our web part to re-render in the event of a query string update: |
| 25 | + |
| 26 | +```typescript |
| 27 | +export default class HelloWorldWebPart extends BaseClientSideWebPart<IHelloWorldWebPartProps> { |
| 28 | + public onInit(): Promise<void> { |
| 29 | + (function (history) { |
| 30 | + var ___pushState = history.___pushState; |
| 31 | + history.___pushState = function (state, key, path) { |
| 32 | + this._onUrlChange(); |
| 33 | + return ___pushState.apply(history, arguments); |
| 34 | + }; |
| 35 | + })(window.history); |
| 36 | + |
| 37 | + window.addEventListener('popstate', function (e) { |
| 38 | + this._onUrlChange(); |
| 39 | + }); |
| 40 | + |
| 41 | + return Promise.resolve(); |
| 42 | + } |
| 43 | + |
| 44 | + public render(): void { |
| 45 | + this.domElement.innerHTML = window.___location.query; |
| 46 | + } |
| 47 | + |
| 48 | + private _onUrlChange(): void { |
| 49 | + // any logic you might want to trigger when the query string updates |
| 50 | + // e.g. fetching data |
| 51 | + this.render(); |
| 52 | + } |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +There are two parts to what we are doing in onInit: |
| 57 | +1. Ensuring that whenever ___pushState is called by other javascript we trigger our `_onUrlChange` method. |
| 58 | +2. Ensuring that whenever the browser fires a 'popstate' event (e.g. user pressing the browser back button) we trigger our `_onUrlChange` method. |
| 59 | + |
0 commit comments