[SalesForce] Get Lightning domain name from Visualforce page and vice-versa

I am using visualforce page inside a lightning component as an iframe. For communication, i use parent.postmessage(message, origin);. Problem is, that at the moment i have hardcoded URL's, but when i deploy to production the domain names will be different.

In lightning experience, i need visualforce URL to confirm, that the message is coming from an expected origin.

How can i get lightning experience domain from visualforce and how can i get visualforce domain name from lightning experience?

Best Answer

I use a class below for this purpose:

public without sharing class UTIL_Domain {

    public static String getVisualforceDomain(){
        return getMyDomain() + '--c.' + getInstance() + '.visual.force.com';
    }

    public static String getLightningDomain(){
        return getMyDomain() + '.lightning.force.com';
    }

    public static String getMyDomain(){
        return URL.getOrgDomainUrl().getHost().split('\\.')[0].toLowerCase();
    }

    private static String instance = '';
    public static String getInstance(){
        if(String.isBlank(instance)){
            instance = [SELECT InstanceName FROM Organization LIMIT 1].InstanceName.toLowerCase();
        }
        return instance;
    }

}
Related Topic