This example demonstrates how to enhance results by incorporating evidence
from client-side JavaScript.
This approach is required to perform certain tasks such as identify iPhone
and iPad models or get the screen resolution for a desktop device.
Properties containing JavaScript snippets are populated by engines in the
Pipeline and these are then bundled together into a single JavaScript
block by the 'JsonBuilder' and 'JavaScriptBuilder' elements.
This JavaScript is then used to obtain the additional evidence from the
client and pass it back to the server. The updated results can then be
used immediately on the client-side or on subsequent requests to the server.
const FiftyOneDegreesDeviceDetection = require((process.env.directory || __dirname) + '/../../');
const myResourceKey = process.env.RESOURCE_KEY || "!!YOUR_RESOURCE_KEY!!";
let server;
if (myResourceKey == "!!YOUR_RESOURCE_KEY!!") {
console.log('You need to create a resource key at ' +
'https://configure.51degrees.com and paste it into the code, ' +
'replacing !!YOUR_RESOURCE_KEY!!');
} else {
const pipeline = new FiftyOneDegreesDeviceDetection.DeviceDetectionPipelineBuilder({
resourceKey: myResourceKey,
javascriptBuilderSettings: {
endPoint: '/json'
}
}).build();
pipeline.on('error', console.error);
const http = require('http');
server = http.createServer((req, res) => {
const flowData = pipeline.createFlowData();
flowData.evidence.addFromRequest(req);
flowData.process().then(function () {
res.statusCode = 200;
if (req.url.startsWith('/json')) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(flowData.jsonbundler.json));
} else {
res.setHeader('Content-Type', 'text/html');
let output = '';
if (flowData.device.hardwarename && flowData.device.hardwarename.hasValue) {
console.log("Client's updated hardware name is " + flowData.device.hardwarename.value);
}
if (flowData.device.screenpixelswidth.hasValue && flowData.device.screenpixelswidth.value) {
console.log("Client's screen pixel width is " + flowData.device.screenpixelswidth.value);
}
output += `
<p id=hardwarename></p>
<p id=screenpixelwidth></p>
<script>
window.onload = function(){
fod.complete(function (data) {
if(data.device["hardwarename"]){
document.getElementById('hardwarename').innerHTML = "<strong>Updated Hardware Name from client-side evidence:</strong> " + data.device["hardwarename"];
}
document.getElementById('screenpixelwidth').innerHTML = "<strong>Pixel width: " + data.device.screenpixelswidth + "</strong>"
});
}
</script>
`;
const js = `<script>${flowData.javascriptbuilder.javascript}</script>`;
res.end(js + output);
}
});
});
const port = 3000;
server.listen(port);
console.log('Server listening on port: ' + port);
}