LWC: Is it safe to rely on window.location.href to get the page url?

You can check Secure Wrappers and Locker API Viewer to get good idea - but it seems to have access and no documentation which says the access would be revoked.

However, the recommended way of getting page reference is through using NavigationMixin & CurrentPageReference.

Sample code JS:

import { LightningElement, wire, api, track } from 'lwc';
import { NavigationMixin, CurrentPageReference } from 'lightning/navigation';

export default class Poc extends NavigationMixin(LightningElement) {
    @wire(CurrentPageReference)
    getpageRef(pageRef) {
        console.log('data => ', JSON.stringify(pageRef));
    }
}

Output:

When above component was used in Aura component (Name:POC_AURA) which was loaded directly (isUrlAddressable interface), we get below object as logged:

{
  "type": "standard__component",
  "attributes": {
    "componentName": "c__POC_AURA"
  },
  "state": {
    "c__id": "some_id"
  }
}

When the same LWC component is put in record page of account, we get below logged:

{
  "type": "standard__recordPage",
  "attributes": {
    "objectApiName": "Account",
    "recordId": "0010K000028HCgAQAW",
    "actionName": "view"
  },
  "state": {

  }
}

You can refer to different pageReference types that you get.


The best I can find is that when you use window, locker service returns a secureWindow object with some differences. You can find the differences here but it doesn't go into detail what those differences are.

You can test functionality in the locker console