After Summer 18 release (API version 43 and up) we can do this.
Implement lightning:isUrlAddressable
interface and use pageReference
attribute.
Example. - Component
Assume url is https://<instance>.lightning.force.com/lightning/cmp/<namespace>__componentName?testAttribute=abc
<aura:component implements="lightning:isUrlAddressable">
<aura:handler name="init" value="{!this}" action="{!c.doInit}" description="Handler for valueInit event fired when the component has been initialised"/>
{!v.pageReference.state.testAttribute}
</aura:component>
Component Controller
({
doInit : function(component, event, helper) {
console.log(component.get("v.pageReference").state.testAttribute);
}
})
Console output will look like: "abc"
This is a limitation, you cannot access the URL parameters in lightning components via an expression tag .
If the hashed part of the URL is changing then there is a neat event to handle and you can read what has changed
aura:locationChange event
If your URL hash is not changing then you can use javascript to do this in your controller.js using below code
doInit: function(component, event, helper) {
// This is url query parameter
var value = helper.getParameterByName(component , event, 'variable');
// Set the value, assumes you have created attribute "attributename" in your markup
component.set("attributename", value);
}
and your helper.js will have a common function to read URL parameter
getParameterByName: function(component, event, name) {
name = name.replace(/[\[\]]/g, "\\$&");
var url = window.location.href;
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Best Answer
Welcome to StackExchange, Gaurav!
As of the Summer '18 release, you can use the lightning:isUrlAddressable interface to expose the page URL via the pageReference attribute, like this:
Include the interface name in the "implements" parameter of your component tag:
Then, in your javascript controller, you can get the value for any property in the URL querystring by reference to the page state:
If your URL has OpportunityId=12345 in the querystring, this will set the oppId attribute equal to 12345: