Identifying OpenLayers 3 version at runtime?

Searching through the OL code reveals that the version number is included in only two places. Firstly, in the comments on the 3rd line. So if you wanted you could parse the ol.js file itself. But that would be a bit messy.

Secondly, the version number is included in the ol.AssertError message as part of the URL that the error links to. So you can get it by forcing an error to be thrown within a try/catch, and then process the resulting error message to extract the version. This is a bit of a hack, but it works for recent versions at least, and it is likely to work for future versions (but no guarantee!).

The format of the general error message is:

Assertion failed. See https://openlayers.org/en/v3.20.0/doc/errors/#41 for details.

This method relies on this format not changing too much, so you should also do some check afterwards (not included here) to make sure that the result is actually just digits and "." characters (and if not, assign some safe default value like "version could not detected").

Here's what worked for me:

var version;
try {
    var layer = new ol.layer.Vector({ style: new ol.style.Circle({ radius: 30 }) });
}
catch(err) {
    var parts = err.message.split("/v");
    parts = parts[parts.length - 1].split("/");
    version = parts[0];
}
console.log(version);

Code Explanation

  1. Within a try block, throw an OL error (in this case, I passed a non-style data where a style was expected).
  2. In the accompanying catch block, split the error message by the "/v" that occurs immediately before the version number. The version number will then be the first part of the last element of the resulting array.
  3. Then split the last element of that array by "/" (first character after the version number).
  4. Assign the first element of the new array to the version variable.

As of OpenLayers 4.1.0, the version number can be accessed through the ol.VERSION variable.

Tags:

Openlayers