JS获取Ip地址、浏览器信息及用户停留时间的方法

发布时间:2021-01-24编辑:脚本学堂
本文介绍下,在c#代码中,借助js获取ip地址、浏览器的信息,以及用户停留时间并写入数据库的例子。有需要的朋友参考下。

js获取用户的IP地址,浏览器的相关信息,以及用户停留时间。

1,Default.aspx
 

复制代码 代码示例:
<script src="jquery.js" type="text/javascript"></script> 
   <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>   
  <script src="JS.js"></script> 

2,JS.js
 

复制代码 代码示例:

var fromURL; 
var IP = returnCitySN["cip"]; 
var city = returnCitySN["cname"]; 
var Browse; 
 
window.onload = function () { 
 
    fromURL = window.document.referrer; 
    if (fromURL == "") { 
        fromURL = "NOFromSource"; 
    } 

 
var Sys = {}; 
var ua = navigator.userAgent.toLowerCase(); 
var s; 
(s = ua.match(/msie ([d.]+)/)) ? Sys.ie = s[1] : 
(s = ua.match(/firefox/([d.]+)/)) ? Sys.firefox = s[1] : 
(s = ua.match(/chrome/([d.]+)/)) ? Sys.chrome = s[1] : 
(s = ua.match(/opera.([d.]+)/)) ? Sys.opera = s[1] : 
(s = ua.match(/version/([d.]+).*safari/)) ? Sys.safari = s[1] : 0; 
/*测试*/ 
if (Sys.ie) Browse = 'IE: ' + Sys.ie; 
if (Sys.firefox) Browse = 'Firefox: ' + Sys.firefox; 
if (Sys.chrome) Browse = 'Chrome: ' + Sys.chrome; 
if (Sys.opera) Browse = 'Opera: ' + Sys.opera; 
if (Sys.safari) Browse = 'Safari: ' + Sys.safari; 
if (Sys.ie == 6.0) { Browse = 'IE: ' + Sys.ie } 

var start = new Date(); 
var time; 
window.onbeforeunload = function () { 
    var end = new Date(); 
    time = end.getTime() - start.getTime(); 
    time = time / 1000; 
    $(function () { 
        $.ajax({ 
            type: "POST", 
            contentType: "application/json", 
            url: "WebService.asmx/Receive", 
            data: "{IP:'" + IP + "',city:'" + city + "',fromURL:'" + fromURL + "',Browse:'" + Browse + "',time:'" + time + "'}", 
            dataType: 'json', 
            success: function (result) { 
             //window.document.write(result.d); 
            } 
        }); 
    }); 
 
    return ; 
}; 

3,web.config
 

复制代码 代码示例:
<add name="Table" connectionString="Data Source=HUGO-PCSQLEXPRESS;Initial Catalog=test;Integrated Security=SSPI" providerName="System.Data.SqlClient" /> 
/connectionStrings> 

4,webService.cs
 

复制代码 代码示例:
[WebMethod]   
public void Receive(string IP, string city, string fromURL, string Browse, string time) 
{      
    string connStr = ConfigurationManager.ConnectionStrings["Table"].ConnectionString; 
    SqlConnection conn = new SqlConnection(connStr); 
    conn.Open(); 
    SqlCommand cmd = new SqlCommand(); 
    cmd.Connection = conn; 
    cmd.CommandText = "insert into ssk(time) values('456')"; 
    cmd.ExecuteNonQuery(); 
    conn.Close(); 
 
    //return "456";