Using 51Degrees Cloud API with JavaScript


9/12/2016 11:06 AM

Device Detection JavaScript Cloud 51Degrees Development

With today’s modern web infrastructures the implementation possibilities for your website are endless; there are many languages you can build your website on, and a plethora of CMS providers to choose from. Whilst some of these can be quite restrictive, the one thing that almost every website is able to use is JavaScript. This blog is aimed at those who may not be able to use languages such as Java or .NET to access our cloud service and shows you how to get it working with nothing more than basic JavaScript.

This snippet will go through a key implementation feature, whilst a full tutorial can be found in the Developer Documentation. In the example below I demonstrate how you can redirect to three different webpages depending on whether the connecting device is a mobile, a tablet or neither.

<!DOCTYPE html> <html> <script> var xmlhttp = new XMLHttpRequest() <!-- Insert Cloud key here. --> var key = "Key" <!-- Receives UserAgent from clients connection. --> var ua = window.navigator.userAgent <!-- Lists the properties required. --> var url = ("https://cloud.51degrees.com/api/v1/"+key+"/match?user-agent="+ua+"&Values=IsMobile+IsTablet") <!-- Parses the JSON object from our cloud server and returns values. --> xmlhttp.onreadystatechange = function(){ if ( xmlhttp.readyState == 4 && xmlhttp.status == 200){ var match = JSON.parse(xmlhttp.responseText) <!-- Redirects dependant on device detected --> if(match.Values.IsTablet == true){ window.location.replace("/Tablet") } else if(match.Values.IsMobile == true){ window.location.replace("/Mobile") } else{ window.location.replace("") } <!-- If neither do nothing and continue to home page --> } } <!-- Sends request to server. --> xmlhttp.open("GET", url, true) xmlhttp.send() </script> </html>

This code checks the API for the clients UA and directs the user to the relevant page for their device. You could easily adapt this for advertisements, links or phone numbers displayed on specific devices.

For more information on our cloud service, or our other on premise solutions, contact us and a member of our team will be happy to assist.