65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用 Script Manager 检测客户端浏览器上的 JavaScript 状态

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (3投票s)

2009 年 4 月 12 日

CPOL

2分钟阅读

viewsIcon

78730

downloadIcon

500

本文档解释了如何使用脚本管理器检测客户端浏览器上的 JavaScript 状态。

引言

确定客户端浏览器是否能够运行 JavaScript 很容易(Request.Browser.JavaScript),但确定客户端是否在其浏览器中启用了此功能则变得有些棘手。

背景

我尝试了许多方法,并发现这是检测客户端浏览器上 JavaScript 活动状态的最有效(免费)方法。

使用代码

代码在 JSDetect.cs 页面中(将执行 JavaScript 状态检测的页面)。我添加了注释来解释其行为。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace JSDetect
{
    public partial class JSDetect : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //sets initial assumption of javascript status 0 = false
            Session["jsActive"] = 0;
            //Set the script manager to run the page method
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), 
              "JSDetect", "PageMethods.SetJSEnabled();", true);
            //Sets the meta refresh to redirect to refering
            //url 2 <-seconds; url <- url to go to 
            refreshCommand.Content = "2; url=" + 
               Request.QueryString["url"].ToString();
        }

        /// <summary>
        /// a Webmethod that is also marked as a script method
        /// so that it can be called from javascript
        /// </summary>
        [WebMethod]
        [System.Web.Script.Services.ScriptMethod()]
        public static void SetJSEnabled()
        {
            //Method called from javascript and sets the jsActive session to 1 = true
            HttpContext.Current.Session["jsActive"] = 1;
            HttpContext.Current.Response.Redirect(
              HttpContext.Current.Request.QueryString["url"].ToString());
              //move back to refering url
        }
    }
}

JSDetect.aspx 页面中,页眉中有一个 meta refresh 标签,用于在没有任何操作发生时重定向到调用页面。添加到 form 标签的脚本管理器需要将 EnablePageMethods 属性设置为 true 才能运行 Web 方法。

<%@ Page Language="C#" AutoEventWireup="true" 
  CodeBehind="JSDetect.aspx.cs" Inherits="JSDetect.JSDetect" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title></title>
<meta id="refreshCommand" runat="server" 
   HTTP-EQUIV="REFRESH" content=""> 
</head>
<body>
    <form id="jsTest" runat="server">
    <asp:ScriptManager ID="smanjs" 
      runat="server" EnablePageMethods="true">
  
    </asp:ScriptManager>
    <div id="ContentDiv" runat="server">
    
    </div>
    </form>
</body>
</html>

现在,要在您的应用程序页面中调用此页面,如您所见,正在引用会话。如果会话不存在,它将进行检查。这在会话超时的情况下很有用。此外,我添加了一些代码来跳过搜索引擎的这一步骤。

我将检测方法设为 public static,并使用 HttpContext 类,以便于将此方法移动到外部库中。

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;

namespace JSDetect
{
    public partial class _Default : System.Web.UI.Page
    {
        bool jsEnabled = false;
        //run anuder initial assumption that JS is disabled

        protected void Page_Load(object sender, EventArgs e)
        {
            jsEnabled = IsJavascriptActive();
            
            Response.Write("Javascript running in browser: " + jsEnabled);
        }
        /// <summary>
        /// Detects whether or not the browser has javascript enabled
        /// </summary>
        /// <returns>boolean indicating if javascript
        // is active on the client browser</returns>
        public static bool IsJavascriptActive()
        {
            bool active = false;
            HttpContext context = HttpContext.Current;
            if (!context.Request.Browser.Crawler)
            {
                if (context.Session["jsActive"] == null)
                {
                    context.Response.Redirect(ClientDomainName() + 
                      "/JSDetect.aspx?url=" + 
                      context.Request.Url.AbsoluteUri.ToString() + 
                      " ", true);
                }
                else
                {
                    if (context.Session["jsActive"].ToString().Equals("0"))
                    {
                        active = false;
                    }
                    else if (context.Session["jsActive"].ToString().Equals("1"))
                    {
                        active = true;
                    }
                }
                
            }
            return active;
        }
        /// <summary>
        /// Get the Domain name and port of the current URL
        /// </summary>
        /// <returns>Domain name and port</returns>
        public static string ClientDomainName()
        {
            string domainNameAndPort = 
              HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, 
              HttpContext.Current.Request.Url.AbsoluteUri.Length - 
              HttpContext.Current.Request.Url.PathAndQuery.Length);
            return domainNameAndPort;
        }
    }
}

关注点

我为自己没有早点想到这一点而感到懊恼,因为我已经使用 AJAX 做了非常类似的事情。我通过研究 Dropthings.com 拖放服务中的代码,获得了 Java / 服务器调用的知识。

这也可以嵌入到您的默认页面中,而无需使用额外的页面,但它是为了重用该方法而构建的。

© . All rights reserved.