如何知道JS代码是在浏览器中还是在设计模式下执行

时间:2015-06-27 13:44:06

标签: javascript intellisense

我相信intellisense可以解决很多时间和错误。假设我打了一个ajax电话,我知道我会得到一系列汽车。

 $.ajax({
        type: "POST",            
        url: "GetCars.aspx",
        success: function (cars) {                

            for(var i = 0; i < cars.length; i++)
            {
                var car = cars[i];
                if(document.designMode)
                {
                   car = { type: "", model: 0, colors: new Array() };
                }
                // Intelissense wors great in here!

                // car.   "the moment I type the '.' I see type, model, and colors

            }
        }            
    });

我需要在visual studio编辑器中返回true并在浏览器中返回false的内容。 if(document.designMode)在VS和浏览器中返回true,因此始终执行行car = { type: "", model: 0, colors: new Array() };我不希望仅在VS上的浏览器上执行第car = { type: "", model: 0, colors: new Array() };行,因此我获得了intellisense 。我怎么能这样做?

解决方案

感谢@Shoms,我提出了:

    var car = null;        

    if (window.navigator.userAgent.length === 212) {         
        car = { type: "", model: 0, colors: new Array() };
    }

    // Intellizense works great :)

请注意您的VS可能需要不同的号码。对我来说,我必须尝试&gt;然后500&lt; 250,&lt; 125等,直到我发现它的长度为212.

1 个答案:

答案 0 :(得分:3)

您可以检查userAgent并根据它确定要执行的操作。 您甚至可以在某些浏览器中设置自定义userAgent,以备不时之需。

window.navigator.userAgent

因此,例如,您的情况可能是:

if(window.navigator.userAgent.indexOf('Mozilla') !== -1) {
   // browser here
} else {
   // VS here (or a non-Mozilla browser, but that's not relevant for development)
   car = { type: "", model: 0, colors: new Array() };
}
相关问题