简体   繁体   中英

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. :-)

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."); } 

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM