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

How to know if JS code is executing in browser or in design mode

本文关键字:执行 设计模式 何知道 JS 浏览器 代码      更新时间:2023-09-26

我相信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
            }
        }            
    });

我需要一些在visualstudio编辑器中返回true,在浏览器中返回false的东西。CCD_ 1在VS和浏览器中返回true,因此始终执行行CCD_我不希望car = { type: "", model: 0, colors: new Array() };行只在VS上的浏览器上执行,所以我得到了intellisense。我该怎么做?


解决方案

感谢我想出的@Shoms:

    var car = null;        
    if (window.navigator.userAgent.length === 212) {         
        car = { type: "", model: 0, colors: new Array() };
    }
    // Intellizense works great :)

请注意,您的VS可能需要不同的编号。对我来说,我必须尝试>500,然后<250,<125等,直到我发现它的长度是212。

您可以检查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() };
}