Defining a new OS line in JavaScript

I am creating a file to be downloaded by the user, and I want to insert the correct newline for my platform ( \n , \r or \r\n ).

I know the following solutions, but no one solves my problem:

  • Request navigator.platform or navigator.appVersion . These properties are deprecated , so I would rather not rely on them.
  • There are special approaches for Firefox and NodeJS . They do not apply since I am building a website and I would prefer it to work on all browsers.
  • There are ways to find newline characters , but I'm interested in the user platform. (They are different: Firefox always uses \n , regardless of the OS.)
+7
javascript newline
source share
2 answers

After a little investigation, I can not find anywhere but the link in the mdn article that says navigator.platform out of date.

Both WHATWG specs and W3 specs still include it in their life standards, and there are no comments on obsolescence.

Actually, the w3 working group asked the Firefox team in January to remove navigator.oscpu or to make it an alias to navigator.platform , since the first is used only by this browser.

Note. The mdn page indicates that it is deprecated after September 2, 2014 , but I'm not sure what motivated this editing.

In any case, I think that you can safely use this navigator.platform property to determine which OS the user is running on (bearing in mind that this information can be faked by the user, but then this is their problem right?)

Edit

Got a response from @Teoli, who did this editing back in 2014:
Question:

Why is navigator.platform marked as deprecated https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform ...?

Answer:

Since the specification asked the browser provider to put as little information as possible in order to avoid fingerprints. Room '' would be a specification. Do not rely on him.

Link to the specified specification request.

+2
source share

Parsing navigator.userAgent can be a fairly reliable way to detect the OS and, therefore, use a newline.

Something like this would probably do the trick - it might take some tweaking on UA ​​strings that are tested for individual platforms.

Also, this will not work if the UA is tampered with.

 function getLinebreak (){ var linebreaks = { Windows: "\r\n", Mac: "\n", Linux: "\n" } for(key in linebreaks){ if(navigator.userAgent.indexOf(key) != -1){ return linebreaks[key]; } } return "\n"; } 

Note. You can probably just check to see if Windows otherwise leads \ n in most cases

Something like this will probably work in most cases:

 function getLinebreak(){ if(navigator.userAgent.indexOf("Windows") != -1){ return "\r\n"; } return "\n"; } 
+2
source share

All Articles