- How to find the operating system version using JavaScript?
- 14 Answers 14
- Sign up or log in
- Post as a guest
- Array.prototype.find()
- Сводка
- Синтаксис
- Параметры
- Возвращаемое значение
- Описание
- Примеры
- Пример: поиск простого числа в массиве
- Полифил
- Window
- Constructors
- Properties
- Properties implemented from elsewhere
- Deprecated properties
- Methods
- Methods implemented from elsewhere
- Deprecated methods
- Event handlers
- Event handlers implemented from elsewhere
- Events
How to find the operating system version using JavaScript?
How can I find the OS name and OS version using JavaScript?
14 Answers 14
If you list all of window.navigator ‘s properties using
You’ll see something like this
Note that oscpu attribute gives you the Windows version. Also, you should know that:
I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So ‘Microsoft Edge’ is the new version based on Chromium and the old Edge is now detected as ‘Microsoft Legacy Edge’!
@Ludwig ‘s solution was brilliant. A couple of fixes (which didn’t have to do with operating system, and I couldn’t place as a comment on his original posting because this is too long):
- IE 11 no longer identifies itself as MS IE.
- Chrome on IOS spoofs itself as Safari
JavaScript have access to the window.navigator.platform — a string representing the platform of the browser: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform
Use it to extract whatever details you need (and can). Note that there are no guarantees that the client actually uses that platform since this can easily be modified in many ways.
platform.js seems like a good one file library to do this.
You can use this javascript function to check users’ OS simply
You can find the OS name and version in the navigator object, as others have answered. The standard, cross-browser place to find this information is in the navigator.userAgent property. However, user agent strings vary widely by OS and browser.
So, I created a script to encapsulate this logic and report on the most common OSes and browsers in a familiar way, like http://www.whatsmybrowser.org.
I open-sourced the script and uploaded it to github, https://github.com/keithws/browser-report. Pull requests are welcome!
I’ve created a library for parsing User Agent strings called Voodoo. But be aware that this should not be used instead of feature detection.
What Voodoo does, is that it parses the userAgent string, which is found in the Navigator object (window.navigator). It’s not all browsers that passes a reliable userAgent string, so even though it’s the normal way to do it, the userAgent can not always be trusted.
I fork @Ludwig code and remove necessity of swfobject .
I just use swfobject code for detect flash version.
I can’t comment on @Ian Ippolito answer (because I would have if I had the rep) but according to the document his comment linked, I’m fairly certain you can find the Chrome version for IOS. https://developer.chrome.com/multidevice/user-agent?hl=ja lists the UA as: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1
So this should work:
Haven’t been able to test (otherwise I would have improved his answer) it to make sure since my iPad is at home and I’m at work, but I thought I’d put it out there.
Hey for a quick solution you can consider the following library : UAPARSER — https://www.npmjs.com/package/ua-parser-js
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Sign up or log in
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Array.prototype.find()
Сводка
Метод find() возвращает значение первого найденного в массиве элемента, которое удовлетворяет условию переданному в callback функции. В противном случае возвращается undefined .
Также смотрите метод findIndex() , который возвращает индекс найденного в массиве элемента вместо его значения.
Если вам нужно найти позицию элемента или наличие элемента в массиве, используйте Array.prototype.indexOf() или Array.prototype.includes() соответственно.
Синтаксис
Параметры
Возвращаемое значение
Значение элемента из массива, если элемент прошёл проверку, иначе undefined .
Описание
Метод find вызывает переданную функцию callback один раз для каждого элемента, присутствующего в массиве, до тех пор, пока она не вернёт true . Если такой элемент найден, метод find немедленно вернёт значение этого элемента. В противном случае, метод find вернёт undefined . До Firefox 34 функция callback не вызывалась для «дырок» в массивах (bug 1058394).
Функция callback вызывается с тремя аргументами: значением элемента, индексом элемента и массивом, по которому осуществляется проход.
Если в метод find был передан параметр thisArg , при вызове callback он будет использоваться в качестве значения this . В противном случае в качестве значения this будет использоваться значение undefined .
Метод find не изменяет массив, для которого он был вызван.
Диапазон элементов, обрабатываемых методом find , устанавливается до первого вызова функции callback . Элементы, добавленные в массив после начала выполнения метода find , не будут посещены функцией callback . Если существующие, непосещение элементы массива изменяются функцией callback , их значения, переданные в функцию, будут значениями на тот момент времени когда метод find посетит их; удалённые элементы все ещё будут посещены.
Примеры
Пример: поиск простого числа в массиве
Следующий пример находит в массиве положительных чисел элемент, являющийся простым числом (либо возвращает undefined , если в массиве нет простых чисел).
Полифил
Этот метод был добавлен в спецификации ECMAScript 6 и пока может быть недоступен во всех реализациях JavaScript. Однако, вы можете использовать следующий сниппет в качестве полифила:
Window
The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document.defaultView property.
A global variable, window , representing the window in which the script is running, is exposed to JavaScript code.
The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the JavaScript Reference and the DOM Reference.
In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeTo() and innerHeight . Generally, anything that can’t reasonably pertain to a tab pertains to the window instead.
Constructors
DOMParser DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization. HTMLImageElement.Image Used for creating an HTMLImageElement . HTMLOptionElement.Option Used for creating an HTMLOptionElement . StaticRange This is an experimental API that should not be used in production code.
Read only Returns a StaticRange() constructor which creates a StaticRange object. Worker Used for creating a Web worker. XMLSerializer Converts a DOM tree into XML or HTML source.
Properties
This interface inherits properties from the EventTarget interface and implements properties from the WindowOrWorkerGlobalScope and WindowEventHandlers mixins.
Note that properties which are objects (e.g. for overriding the prototype of built-in elements) are listed in a separate section below.
Window.closed Read only This property indicates whether the current window is closed or not. Window.console Read only Returns a reference to the console object which provides access to the browser’s debugging console. Window.controllers Read only This API has not been standardized.
Returns the XUL controller objects for the current chrome window. Window.customElements Read only Returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements. Window.crypto Read only Returns the browser crypto object. Window.devicePixelRatio Read only Returns the ratio between physical pixels and device independent pixels in the current display. Window.document Read only Returns a reference to the document that the window contains. Window.DOMMatrix Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMMatrix object, which represents 4×4 matrices, suitable for 2D and 3D operations. Window.DOMMatrixReadOnly Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMMatrixReadOnly object, which represents 4×4 matrices, suitable for 2D and 3D operations. Window.DOMPoint Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMPoint object, which represents a 2D or 3D point in a coordinate system. Window.DOMPointReadOnly Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMPointReadOnly object, which represents a 2D or 3D point in a coordinate system. Window.DOMQuad Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMQuad object, which provides represents a quadrilaterial object, that is one having four corners and four sides. Window.DOMRect Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMRect object, which represents a rectangle. Window.DOMRectReadOnly Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMRectReadOnly object, which represents a rectangle. Window.event Read only Returns the current event, which is the event currently being handled by the JavaScript code’s context, or undefined if no event is currently being handled. The Event object passed directly to event handlers should be used instead whenever possible. Window.frameElement Read only Returns the element in which the window is embedded, or null if the window is not embedded. Window.frames Read only Returns an array of the subframes in the current window. Window.fullScreen This property indicates whether the window is displayed in full screen or not. Window.history Read only Returns a reference to the history object. Window.innerHeight Read only Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar. Window.innerWidth Read only Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar. Window.isSecureContext This is an experimental API that should not be used in production code.
Read only Indicates whether a context is capable of using features that require secure contexts. Window.length Read only Returns the number of frames in the window. See also window.frames . Window.location Gets/sets the location, or current URL, of the window object. Window.locationbar Read only Returns the locationbar object, whose visibility can be toggled in the window. Window.localStorage Read only Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it. Window.menubar Read only Returns the menubar object, whose visibility can be toggled in the window. Window.messageManager This API has not been standardized.
Returns the message manager object for this window. Window.mozInnerScreenX Read only This API has not been standardized.
Returns the horizontal (X) coordinate of the top-left corner of the window’s viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in nsIDOMWindowUtils for a conversion factor to adapt to screen pixels if needed. Window.mozInnerScreenY Read only This API has not been standardized.
Returns the vertical (Y) coordinate of the top-left corner of the window’s viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed. Window.name Gets/sets the name of the window. Window.navigator Read only Returns a reference to the navigator object. Window.opener Returns a reference to the window that opened this current window. Window.outerHeight Read only Gets the height of the outside of the browser window. Window.outerWidth Read only Gets the width of the outside of the browser window. Window.pageXOffset Read only An alias for window.scrollX . Window.pageYOffset Read only An alias for window.scrollY Window.parent Read only Returns a reference to the parent of the current window or subframe. Window.performance Read only Returns a Performance object, which includes the timing and navigation attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples. Window.personalbar Read only Returns the personalbar object, whose visibility can be toggled in the window. Window.screen Read only Returns a reference to the screen object associated with the window. Window.screenX and Window.screenLeft Read only Both properties return the horizontal distance from the left border of the user’s browser viewport to the left side of the screen. Window.screenY and Window.screenTop Read only Both properties return the vertical distance from the top border of the user’s browser viewport to the top side of the screen. Window.scrollbars Read only Returns the scrollbars object, whose visibility can be toggled in the window. Window.scrollMaxX This API has not been standardized.
Read only The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width. Window.scrollMaxY This API has not been standardized.
Read only The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height). Window.scrollX Read only Returns the number of pixels that the document has already been scrolled horizontally. Window.scrollY Read only Returns the number of pixels that the document has already been scrolled vertically. Window.self Read only Returns an object reference to the window object itself. Window.sessionStorage Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it. Window.sidebar This API has not been standardized.
Read only Returns a reference to the window object of the sidebar. Window.speechSynthesis Read only Returns a SpeechSynthesis object, which is the entry point into using Web Speech API speech synthesis functionality. Window.status Gets/sets the text in the statusbar at the bottom of the browser. Window.statusbar Read only Returns the statusbar object, whose visibility can be toggled in the window. Window.toolbar Read only Returns the toolbar object, whose visibility can be toggled in the window. Window.top Read only Returns a reference to the topmost window in the window hierarchy. This property is read only. Window.visualViewport Read only This is an experimental API that should not be used in production code.
Returns a VisualViewport object which represents the visual viewport for a given window. Window.window Read only Returns a reference to the current window. window[0] , window[1] , etc. Returns a reference to the window object in the frames. See Window.frames for more details.
Properties implemented from elsewhere
Deprecated properties
This deprecated API should no longer be used, but will probably still work.
Read only Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore. Window.defaultStatus This deprecated API should no longer be used, but will probably still work.
Gets/sets the status bar text for the given window. Window.dialogArguments This deprecated API should no longer be used, but will probably still work.
Read only Gets the arguments passed to the window (if it’s a dialog box) at the time window.showModalDialog() was called. This is an nsIArray . Window.directories This deprecated API should no longer be used, but will probably still work.
Synonym of window.personalbar Window.globalStorage This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Multiple storage objects that were used for storing data across multiple pages. Window.mozAnimationStartTime This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
The time in milliseconds since epoch at which the current animation cycle began. Use Animation.startTime instead. Window.mozPaintCount This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance. Window.orientation Read only This deprecated API should no longer be used, but will probably still work.
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device’s natural orientation. Window.pkcs11 This deprecated API should no longer be used, but will probably still work.
Formerly provided access to install and remove PKCS11 modules. Window.returnValue This deprecated API should no longer be used, but will probably still work.
The return value to be returned to the function that called window.showModalDialog() to display the window as a modal dialog.
Methods
This interface inherits methods from the EventTarget interface and implements methods from WindowOrWorkerGlobalScope and EventTarget .
Window.alert() Displays an alert dialog. Window.blur() Sets focus away from the window. Window.cancelAnimationFrame() This is an experimental API that should not be used in production code.
Enables you to cancel a callback previously scheduled with Window.requestAnimationFrame . Window.cancelIdleCallback() This is an experimental API that should not be used in production code.
Enables you to cancel a callback previously scheduled with Window.requestIdleCallback . Window.clearImmediate() Cancels the repeated execution set using setImmediate . Window.close() Closes the current window. Window.confirm() Displays a dialog with a message that the user needs to respond to. Window.dump() This API has not been standardized.
Writes a message to the console. Window.find() Searches for a given string in a window. Window.focus() Sets focus on the current window. Window.getComputedStyle() Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element. Window.getDefaultComputedStyle() This API has not been standardized.
Gets default computed style for the specified element, ignoring author stylesheets. Window.getSelection() Returns the selection object representing the selected item(s). Window.matchMedia() Returns a MediaQueryList object representing the specified media query string. Window.maximize() FIXME: NeedsContents Window.minimize() (top-level XUL windows only) Minimizes the window. Window.moveBy() Moves the current window by a specified amount. Window.moveTo() Moves the window to the specified coordinates. Window.open() Opens a new window. Window.postMessage() Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first. Window.print() Opens the Print Dialog to print the current document. Window.prompt() Returns the text entered by the user in a prompt dialog. Window.requestAnimationFrame() Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame. Window.requestIdleCallback() This is an experimental API that should not be used in production code.
Enables the scheduling of tasks during a browser’s idle periods. Window.resizeBy() Resizes the current window by a certain amount. Window.resizeTo() Dynamically resizes window. Window.scroll() Scrolls the window to a particular place in the document. Window.scrollBy() Scrolls the document in the window by the given amount. Window.scrollByLines() This API has not been standardized.
Scrolls the document by the given number of lines. Window.scrollByPages() This API has not been standardized.
Scrolls the current document by the specified number of pages. Window.scrollTo() Scrolls to a particular set of coordinates in the document. Window.setImmediate() Executes a function after the browser has finished other heavy tasks Window.setResizable() This API has not been standardized.
Toggles a user’s ability to resize a window. Window.sizeToContent() This API has not been standardized.
Sizes the window according to its content. Window.showOpenFilePicker() Shows a file picker that allows a user to select a file or multiple files. Window.showSaveFilePicker() Shows a file picker that allows a user to save a file. Window.showDirectoryPicker() Displays a directory picker which allows the user to select a directory. Window.stop() This method stops window loading. Window.updateCommands() This API has not been standardized.
Updates the state of commands of the current chrome window (UI).
Methods implemented from elsewhere
Deprecated methods
This deprecated API should no longer be used, but will probably still work.
Moves back one in the window history. This method is deprecated; you should instead use window.history.back() . Window.captureEvents() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Registers the window to capture all events of the specified type. Window.forward() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Moves the window one document forward in the history. This method is deprecated; you should instead use window.history.forward() . Window.home() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Returns the browser to the home page. Window.openDialog() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Opens a new dialog window. Window.releaseEvents() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Releases the window from trapping events of a specific type. Window.showModalDialog() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Displays a modal dialog.
Event handlers
These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.
This interface inherits event handlers from the EventTarget interface and implements event handlers from WindowEventHandlers .
Window.onappinstalled Called when the page is installed as a webapp. See appinstalled event. Window.onbeforeinstallprompt An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile. Window.ondevicelight An event handler property for any ambient light levels changes Window.ondevicemotion Called if accelerometer detects a change (For mobile devices) Window.ondeviceorientation Called when the orientation is changed (For mobile devices) Window.ondeviceorientationabsolute This API has not been standardized.
An event handler property for any device orientation changes. Window.ondeviceproximity An event handler property for device proximity event Window.ongamepadconnected Represents an event handler that will run when a gamepad is connected (when the gamepadconnected event fires). Window.ongamepaddisconnected Represents an event handler that will run when a gamepad is disconnected (when the gamepaddisconnected event fires). Window.onmozbeforepaint An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the window.requestAnimationFrame method. Window.onpaint An event handler property for paint events on the window. WindowEventHandlers.onrejectionhandled An event handler for handled Promise rejection events. Window.onuserproximity An event handler property for user proximity events. Window.onvrdisplayconnect Represents an event handler that will run when a compatible VR device has been connected to the computer (when the vrdisplayconnected event fires). Window.onvrdisplaydisconnect Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the vrdisplaydisconnected event fires). Window.onvrdisplayactivate Represents an event handler that will run when a display is able to be presented to (when the vrdisplayactivate event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on. Window.onvrdisplaydeactivate Represents an event handler that will run when a display can no longer be presented to (when the vrdisplaydeactivate event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity. Window.onvrdisplayblur Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the vrdisplayblur event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience. Window.onvrdisplayfocus Represents an event handler that will run when presentation to a display has resumed after being blurred (when the vrdisplayfocus event fires). Window.onvrdisplaypresentchange represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the vrdisplaypresentchange event fires).
Event handlers implemented from elsewhere
An event handler for unhandled Promise rejection events. WindowEventHandlers.onunload Called when the user navigates away from the page.
Events
Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.
error Fired when a resource failed to load, or can’t be used. For example, if a script has an execution error or an image can’t be found or is invalid.
Also available via the onerror property. languagechange Fired at the global scope object when the user’s preferred language changes.
Also available via the onlanguagechange property. orientationchange Fired when the orientation of the device has changed.
Also available via the onorientationchange property. devicemotion Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available. deviceorientation Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame. resize Fired when the window has been resized.
Also available via the onresize property. storage Fired when a storage area ( localStorage or sessionStorage ) has been modified in the context of another document.
Also available via the onstorage property.