0

I'm working on a scenario wherein I make an apex method call from connectedcallback and try to get the browser context in the apex code but it seems to be throwing an exception. Below is the code:

Apexpages.currentPage().getHeaders().put('X-UA-Compatible', 'IE=10');
            string sBrowserContext=ApexPages.currentPage().getHeaders().get('USER-AGENT');
            system.debug('sBrowserContext : ' +sBrowserContext);
            if(sBrowserContext.contains('Chrome/'))sBrowserId='Chrm';
            if(sBrowserContext.contains('Firefox/'))sBrowserId='FFox';
            if(sBrowserContext.contains('Trident/'))sBrowserId='IE';
            if(sBrowserContext.contains('iPhone'))sBrowserId='iPhn';
            System.debug('sBrowserId : ' +sBrowserId);

This same piece of code works perfectly when called from VF Component. I just want to be sure if we can get the context from the lwc too?

3
  • 1
    Why not use standard javascript? stackoverflow.com/a/16204644 Commented Sep 19, 2019 at 16:43
  • @PranayJaiswal, i was checking same article and verifying if it works in LWC! Commented Sep 19, 2019 at 16:52
  • Out of curiosity, why would you want to do browser detection instead of simply doing feature detection, as you might in modernizr?
    – sfdcfox
    Commented Sep 20, 2019 at 3:31

1 Answer 1

1

You can use this post.

HTML:

<lightning-button label="Get Browser" onclick={printBrowser}></lightning-button>
<div lwc:dom="manual" data-print></div>

JS:

printBrowser() {
    navigator.sayswho = (function() {
        var ua = navigator.userAgent,
            tem,
            M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(M[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE ' + (tem[1] || '');
        }
        if (M[1] === 'Chrome') {
            tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
            if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
        }
        M = M[2] ? [ M[1], M[2] ] : [ navigator.appName, navigator.appVersion, '-?' ];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
        return M.join(' ');
    })();

    console.log(navigator.sayswho);
    this.template.querySelector('[data-print]').innerHTML = navigator.sayswho;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .