打开页面时不会在Chrome中发出提醒

时间:2018-02-21 14:38:13

标签: javascript google-chrome if-statement alert

当用户在Chrome以外的浏览器中打开我的网页时,我试图提示弹出窗口。我有这个:

if(/ 只有在浏览器不是谷歌浏览器时才能在此处显示以下内容? /){     提醒("请使用谷歌浏览器访问此网站。\ n有些主要功能在Chrome以外的浏览器中不起作用。"); }

在此处发现这是一个可能的条件:navigator.userAgent.search(" Chrome"),但无法使其正常工作。请指教。 : - )

2 个答案:

答案 0 :(得分:1)

这应该是它。

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

答案 1 :(得分:1)

正如上面的评论通过引用问题指出的那样,您可以在userAgent中测试chrome。但你想要扭转这一点:

    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)

除非用户欺骗他们的userAgent,否则这将解决问题。这不寻常。要完全检查您还应该检查功能铬是否具有和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)