Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I believe intellisense can solve a lot of time and bugs. Lets say I make an ajax call and I know I will get an array of cars.

 $.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

            }
        }            
    });

I need something that will return true in visual studio editor and false in the browser. if(document.designMode) returns true in VS and in the browser so the line car = { type: "", model: 0, colors: new Array() }; is always executed. I don't want the line car = { type: "", model: 0, colors: new Array() }; to be executed on the browser only on VS so I get intellisense. How can I do that?


Solution

Thanks to @Shoms I came up with:

    var car = null;        

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

    // Intellizense works great :)

Note your VS might require a different number. For me I have to try > 500 then <250 , < 125 etc until I found that it is length 212.

like image 501
Tono Nam Avatar asked Oct 19 '22 08:10

Tono Nam


1 Answers

You can check for the userAgent and decide what to do based on it. You can even set a custom userAgent in some browsers in case you need that too.

window.navigator.userAgent

So, for example, your condition could be:

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() };
}
like image 52
Shomz Avatar answered Oct 22 '22 01:10

Shomz