RavMucha
RavMucha

Reputation: 11

Alert when page opened not in Chrome

I'm trying to get an alert to pop up when the user opens my webpage in a browser other than Chrome. I have this:

if (/what to put here to make the below show only if the browser is not Google Chrome?/) { alert( "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome." ); }

Found this here as a possible condition: navigator.userAgent.search("Chrome"), but can't make it work. Please advise. :-)

Upvotes: 1

Views: 1777

Answers (2)

Jon Wood
Jon Wood

Reputation: 1741

As the comments above point out by referencing questions you can test for chrome in the userAgent. But you would want to reverse that:

    let notChrome = !/Chrome/.test(navigator.userAgent)
    
    let alertMessage = "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome."
    if(notChrome) alert(alertMessage)

This will solve the problem unless the user is spoofing their userAgent. This is unusual though. To fully check you should also check for a feature chrome has AND the userAgent:

        let notChrome = !/Chrome/.test(navigator.userAgent) && !("webkitAppearance" in document.body.style)
        
        let alertMessage = "Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome."
        if(notChrome) alert(alertMessage)

Upvotes: 3

CodeF0x
CodeF0x

Reputation: 2682

This should to it.

var isChrome = !!window.chrome; // "!!" converts the object to a boolean value
console.log(isChrome); // Just to visualize what's happening

/** Example: User uses Firefox, therefore isChrome is false; alert get's triggered */
if (isChrome !== true) { 
  alert("Please use Google Chrome to access this site.\nSome key features do not work in browsers other than Chrome.");
}

Upvotes: 1

Related Questions