How to use useragent - 10 common examples

To help you get started, we’ve selected a few useragent examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dwyl / faster / lib / socketserver.js View on Github external
io.on('connection', function(socket){
  // var ua = socket.handshake.headers['user-agent'].split(' ');
  var agent = useragent.parse(socket.handshake.headers['user-agent']);
  // var agent = ua[ua.length-1];
  var client = socket.id +" " +chalk.cyan(agent);
  console.log(chalk.green("Browser / Device Connected: ") + client);

  // just to test the socket server is accessible from the client
  socket.emit('message', chalk.red('Faster WebSocket Server Says Hi!') );

  // we use the "secret" chanel for refreshing
  socket.on(secret, function(data) {
    var note = ' Sending Refresh Signal to All Connected Devices/Clients '
    console.log(chalk.bgGreen.black(note));
    socket.broadcast.emit('refresh', data);
  }); // which avoids your work colleagues spamming your dev box

  socket.on("disconnect", function() {
    // console.log(chalk.red("Refreshing Device/Browser >> ") + client);
github wolfeidau / winston-request-logger / lib / winston-request-logger.js View on Github external
res.end = function (chunk, encoding) {

            // Our format argument above contains key-value pairs for the output
            // object we send to Winston. Let's use this to format our results:
            var data = {};
            var tokens = {
                ':date': startTime.toISOString(),
                ':statusCode': _colorStatus(res.statusCode),
                ':method': req.method,
                ':responseTime': (new Date() - startTime),
                ':url\\[([a-z]+)\\]': function (str, segment) { return requestedUrl[segment]; },
                ':ip': req.headers['x-forwarded-for'] || req.ip || req.connection.remoteAddress,
                ':userAgent': useragent.parse(req.headers['user-agent']).toString()
            };

            // Do the work expected
            res.end = requestEnd;
            res.end(chunk, encoding);

            // Let's define a default format
            if (typeof(format) !== 'object') {
                format = {
                    date: ':date',
                    status: ':statusCode',
                    method: ':method',
                    url: ':url[pathname]',
                    response_time: ':responseTime',
                    user_agent: ':userAgent'
                };
github JKHeadley / appy-backend / server / api / visitor.api.js View on Github external
const recordVisitorHandler = async function(request, h) {
      try {
        // Specify the iplocation hosts to prevent issues (Ex: docker cant ping "https://ipaip.co/" by default)
        // let hosts = ['freegeoip.net', 'ipapi.co']
        // NOTE: Sign up for free access key at https://ipstack.com/
        let host =
          'http://api.ipstack.com/*?access_key=' +
          Config.get('/ipstackAccessKey') +
          '&format=1'

        let result = await iplocation(server.methods.getIP(request), [host])
        const agent = useragent.parse(request.headers['user-agent'])

        const visitor = Object.assign(result, { browser: agent.family })

        return RestHapi.create(Visitor, visitor, Log)
      } catch (err) {
        errorHelper.handleError(err, Log)
      }
    }
github Lapple / ErrorBoard / server / module-logger.js View on Github external
app.use(function(req, res) {
    var query = req.query;

    if (!query.message || !query.url) {
        return res.end(400);
    }

    var ua = useragent.parse(req.headers['user-agent']).toJSON();
    var referer = req.headers.referer;
    var timestamp = Date.now();
    var date = moment(timestamp).format('DD-MM-YYYY');

    var meta = query.meta;

    try {
        meta = JSON.parse(meta);
    } catch(e) {
        // Unable to parse JSON metadata, treating it as a string.
    }

    var doc = {
        ua: ua,
        referer: referer,
        timestamp: timestamp,
github sergeyksv / tinelic / modules / collectapi.js View on Github external
safe.run(function (cb) {
		data._idp=req.params.project;
		data._dtr = new Date();
		data._dtc = data._dt;
		data._dt = data._dtr;
		data.agent = useragent.parse(req.headers['user-agent']).toJSON();
		var ip = req.headers['x-forwarded-for'] ||
			 req.connection.remoteAddress ||
			 req.socket.remoteAddress ||
			 req.connection.socket.remoteAddress;

		var geo = geoip.lookup(ip);
		if (geo)
			data.geo = JSON.parse(JSON.stringify(geo));

		data = prefixify(data,{strict:1});

		// add few data consistance checks
		if (data._i_tt > 1000 * 60 * 10)
			return cb(new Error("Page total time is too big > 10 min"));

		if (Math.abs(data._i_tt - data._i_nt - data._i_lt - data._i_dt)>1000)
github sergeyksv / tinelic / modules / collect.js View on Github external
ctx.api.assets.ensureProjectId(ctx.locals.systoken, req.params.project, safe.sure(cb, idp => {
							if (!idp) {
								let errSlug = `Browser, bad id ${req.params.project} - ${req.headers.referer||req.headers.origin}`;
								if (errProjectIds.has(errSlug))
									return cb(null);
								errProjectIds.set(errSlug,true); 
								return cb(new Error(errSlug));
							}							
							data._idp = idp;
							data._dtr = new Date();
							data._dtc = data._dt;
							data._dt = data._dtr;
							data.agent = useragent.parse(req.headers['user-agent']).toJSON();
							let ip = req.headers['x-forwarded-for'] ||
								req.connection.remoteAddress ||
								req.socket.remoteAddress ||
								req.connection.socket.remoteAddress;

							let geo = geoip.lookup(ip);
							if (geo)
								data.geo = JSON.parse(JSON.stringify(geo));

							data = prefixify(data, { strict: 1 });

							// add few data consistance checks
							if (data._i_tt > 1000 * 60 * 10)
								return cb(new Error('Page total time is too big > 10 min'));

							if (Math.abs(data._i_tt - data._i_nt - data._i_lt - data._i_dt) > 1000)
github sergeyksv / tinelic / modules / collectapi.js View on Github external
safe.run(function (cb) {
		data = JSON.parse(req.query.sentry_data);
		var ip = req.headers['x-forwarded-for'] ||
			 req.connection.remoteAddress ||
			 req.socket.remoteAddress ||
			 req.connection.socket.remoteAddress;

		var _dtp = data._dtp || data._dtInit;
		if (data.project) delete data.project;
		data._idp = req.params.project;
		data._dtr = new Date();
		data._dtc = data._dt;
		data._dt = data._dtr;
		data._dtp = _dtp;
		if (data._dtInit) delete data._dtInit;
		data.agent = useragent.parse(req.headers['user-agent'],data.request.headers['User-Agent']).toJSON();
		data = prefixify(data,{strict:1});
		var md5sum = crypto.createHash('md5');
		md5sum.update(ip);
		md5sum.update(req.headers.host);
		md5sum.update(req.headers['user-agent']);
		md5sum.update(""+(parseInt(data._dtp.valueOf()/(1000*60*60))));
		data.shash = md5sum.digest('hex');
		md5sum = crypto.createHash('md5');
		md5sum.update(ip);
		md5sum.update(req.headers.host);
		md5sum.update(req.headers['user-agent']);
		md5sum.update(data._dtp.toString());
		data.chash = md5sum.digest('hex');
		// when error happens try to link it with current page
		// which is latest page from same client (chash)
		// which is registered not later than current event
github DevExpress / testcafe / src / browser-connection / index.js View on Github external
establish (userAgent) {
        this.ready     = true;
        this.userAgent = parseUserAgent(userAgent).toString();

        this._waitForHeartbeat();
        this.emit('ready');
    }
github mikey1384 / twinkle-network / api / controllers / user.js View on Github external
router.post('/action/logout', requireAuth, (req, res) => {
  const { user } = req
  const userAgent = useragent.parse(req.headers['user-agent']).toString()
  return poolQuery(`INSERT INTO users_actions SET ?`, {
    userId: user.id,
    action: 'logout',
    userAgent,
    ip: req.ip,
    timeStamp: Math.floor(Date.now() / 1000)
  })
    .then(() => res.send(true))
    .catch(error => {
      console.error(error)
      res.status(500).send({ error })
    })
})
github jesseditson / Urza / lib / helpers / middleware / useragent.js View on Github external
var UserAgent = module.exports = function(req,res,next){
  if(config.mobileOnly){
    req.isMobile = true;
  } else if(config.webOnly){
    req.isMobile = false;
  } else {
    var ua = useragent.parse(req.headers['user-agent']).toString(),
        mobilePattern = /(ios|mobile|android|wii|webos|tablet|kindle|portable|palm|symbian|blackberry)/i
    //console.log("User Agent Info: ",ua,ua.match(mobilePattern),useragent.is(req.headers['user-agent']).mobile_safari)
    if(ua.match(mobilePattern) || useragent.is(req.headers['user-agent']).mobile_safari){
      if(ua.match(/ipad/i)){
        req.isMobile = 'iPad';
      } else {
        req.isMobile = true;
      }
    } else {
      req.isMobile = false;
    }
  }
  next();
}

useragent

Fastest, most accurate & effecient user agent string parser, uses Browserscope's research for parsing

MIT
Latest version published 7 years ago

Package Health Score

41 / 100
Full package analysis

Popular useragent functions