[SalesForce] URL Parameter Retrieval Not Working In Lightning LWC Component

I have a situation where a user makes a change inside a Lightning page which uses web components. This page then sets parameters on to the URL and redirects to the same Lightning page.

The redirect code in the page is as follows –

window.location.replace(window.location.href + '?ObjectName=' + encodeURIComponent(this.listViewObject) 
                                             + '&ListViewName=' + encodeURIComponent(this.listViewName));

(the page is calling itself but with two additional parameters. This use-case might seem strange but I have good reasons!)

An example redirect URL looks as follows –

https://simpli-list-view-dev-dev-ed.lightning.force.com/lightning/n/simpli_lv__List_Views_Example_1?ObjectName=Account&ListViewName=PlatinumandGoldSLACustomers

As can be seen the parameters retrieved should be –

  • ObjectName – Account
  • ListViewName – PlatinumandGoldSLACustomers

I have looked around the web and it looks like I should be able to retrieve these parameters in the following way –

renderedCallback() {

    let params = new URL(window.location.href).searchParams;
            
    this.urlObject = params.get('ObjectName');
    this.urlListView = params.get('ListViewName');
}

From what I understand this needs to be done in the renderedCallback() method so that we have access to the main objects variables. i.e. urlObject and urlListView.

The redirect code looks to work fine. When I run the code I see the page refresh and I see the URL get updated with the additional parameters. But, when the renderedCallback() method is run the parameters are null.

What am I doing wrong?

Am I not calling the URL object or retrieving the params correctly?

I have noticed that soon after the redirect refreshes the page, the URL reverts back to the URL without the parameters. i.e.

https://simpli-list-view-dev-dev-ed.lightning.force.com/lightning/n/simpli_lv__List_Views_Example_1

Am I doing this in a totally incorrect way or am I just missing something?

Best Answer

You should try to stay away from the window object in LWC.

Locker intercepts calls to window and uses SecureWindow instead.

You can read more here.

In your lightning web component try using this

    import { LightningElement, wire } from 'lwc';
    import { CurrentPageReference } from 'lightning/navigation';
    
    export default class Sample extends LightningElement {
    
        @wire(CurrentPageReference)
        currentPageReference;
    
        connectedCallback() {
            console.log('ObjectName is: ' + this.currentPageReference.state.ObjectName );
            console.log('ListViewName is: ' + this.currentPageReference.state.ListViewName );
        }
    }

Source.

Related Topic