程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 用C#代碼修改FF和IE的Script狀態

用C#代碼修改FF和IE的Script狀態

編輯:關於C#

這兩天一直研究如何通過代碼來實現對IE和FF裡面設置的操作,來達到更改IE中的Script或者是JavaScript的狀態,是disabled還是enabled。以下介紹的心得暫時還不支持其它浏覽器。

暫時發現的方案有2個(以IE為例)

其一,用自動化的某個工具,抓取IE的process id等,然後抓取IE的那些files,tools,菜單項,一步一步的點擊,抓取,然後再點擊,保存。

其二,寫代碼,修改現有的一些能夠更改的資源,實現其狀態的讀取和修改。

對於以上的兩個方案,本文只實現了後者,原因是前者需要的自動化工具不好確定,就算是確定了也需要一段時間對環境的配置,文檔的閱讀,熟悉那些dll等等,這會花費大量的時間。而對於後種解決方案來說,會省時。

IE

注冊表詳細信息如下:http://support.microsoft.com/kb/182569

Internet Explorer 安全區域注冊表項說明中有一部分提到的如下的內容,那麼我們就可以通過修改注冊表中的選項來達到我們預期的要求。

/// <summary>
        /// Get Current Script state of IE.
        /// </summary>
        /// <param name="regPath"></param>
        /// <returns>true ---> allow Script.</returns>
        public static bool GetIECurrentScriptState(string regPath)
        {
            bool ret = false;
            RegistryKey regSubkey = null;
            regSubkey = Registry.CurrentUser.OpenSubKey(regPath, true);
            if (regSubkey.GetValue("1400").ToString() == "0")
            {
                ret = true;
            }
            if ((int)regSubkey.GetValue("1400") == 3)
            {
                ret = false;
            }

            return ret;
        }

以下是對IE中注冊表的改變:

/// <summary>
        /// Disable IE Scripts.
        /// </summary>
        public void DisableIEScripts()
        {
            RegistryKey regSubKey = null;
            regSubKey = Registry.CurrentUser.OpenSubKey(regPath, true);
            regSubKey.SetValue("1400", 0x3);
        }

起初我以為如此修改注冊表的信息也會帶來其他浏覽器的改變,但是結果並不然。

FireFox

當我企圖在FF裡面尋找相關注冊表修改的時候,並沒有找到相關選項,於是換一種思路。最終在當前用戶的firefox文件中,找到了一個叫做pref.js的文件。裡面有也許有一行代碼,user_pref("javascript.enabled", false); 。這就代表了javascript被禁止了。如果為true或者沒有的話,那麼都代表了允許狀態。而該文件的文件夾9acap8nw.default如此帶有default字樣的,也是隨著不同的機器安裝不同的客戶端所不同的。而它的前面的目錄大概的C:\Documents and Settings\。。。\Application Data\Mozilla\Firefox\Profiles如此。不過會有這樣的文件夾也只是在windows server2003 和XP中有如此的目錄,具體問題還是需要具體分析的。

/// <summary>
        /// Delete one line which contains the "javaScript.enabled.
        /// </summary>
        /// <param name="filePath">the path of js file.</param>
        public static void DisableFFJaveScript(string filePath)
        {
            StringBuilder sb = new StringBuilder();
            using (FileStream aStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                StreamReader aReader = new StreamReader(aStream, Encoding.UTF8);
                StreamWriter aWriter = new StreamWriter(aStream, Encoding.UTF8);
                aReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string streamLine = aReader.ReadLine();
                bool isJSDisabled = false;
                bool isJSFalse = false;
                while (streamLine != null)
                {
                    if (streamLine.Contains("javascript.enable") && streamLine.Contains("false"))
                    {
                        isJSFalse = true;
                    }
                    if (streamLine.Contains("javascript.enable") && streamLine.Contains("true"))
                    {
                        streamLine = streamLine.Replace("true", "false");
                        isJSDisabled = true;
                    }

                    sb.Append(streamLine + "\r\n");
                    streamLine = aReader.ReadLine();
                }

                if (!isJSDisabled && !isJSFalse)
                    sb.Append("user_pref(" + "\"javascript.enabled\"" + "," + " false);");
                aReader.Close();
            }

            File.Delete(filePath);
            AddToFile(filePath, sb.ToString());
        }

附下全部源碼供大家分享。包括對當前文件路徑的組合,文件讀取,增刪改操作。IE,FF,狀態的讀取,改變。

有一切問題都歡迎拍磚:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Security.Principal;
using Microsoft.Win32;
namespace FileLoadAndModify
{
public class Program
{
public static void Main(string[] args)
{
//There exists two methods to get the current user info.
//Because the folder in generate by random and the file path includes the user alias infro.
//So we have to combine the strings to generate it.
string filePath = GetUserFilePathByXMLWithoutConfig();
string regPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\";
//string filePath = GetUserFilePathByXMLWithConfig();
string fileName = string.Empty;
DirectoryInfo dicInfo = new DirectoryInfo(filePath);
DirectoryInfo[] dicFolder = dicInfo.GetDirectories();
foreach (DirectoryInfo dicInfoFolder in dicFolder)
{
if(dicInfoFolder.FullName.Contains(".default"))
{
filePath += dicInfoFolder.Name + @"\";
}
}
dicInfo = new DirectoryInfo(filePath);
FileInfo[] filesInDir = dicInfo.GetFiles();
foreach (FileInfo file in filesInDir)
{
if (file.FullName.Contains("prefs.js"))
{
filePath += file.Name;
}
}
bool state = GetFFCurrentJavaScripState(filePath);
EnableFFJavaScript(filePath);
DisableFFJaveScript(filePath);
GetIECurrentCookiesState(regPath);
GetIECurrentScriptState(regPath);
}
/// <summary>
/// Get Current FireFox JavaScript state
/// </summary>
/// <param name="filePath"></param>
/// <returns>true ---> enable/ false ----> disabled.</returns>
public static bool GetFFCurrentJavaScripState(string filePath)
{
bool ret = false;
using (FileStream aStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
StreamReader aReader = new StreamReader(aStream, Encoding.UTF8);
aReader.BaseStream.Seek(0, SeekOrigin.Begin);
string streamLine = aReader.ReadLine();
while (streamLine != null)
{
if ((streamLine.Contains(@"javascript.enabled") && streamLine.Contains("true")) || !streamLine.Contains(@"javascript.enabled"))
{
ret = true;
}
streamLine = aReader.ReadLine();
}
aReader.Close();
}
return ret;
}
/// <summary>
/// Enable FireFox javascript
/// </summary>
/// <param name="filePath"></param>
public static void EnableFFJavaScript(string filePath)
{
StringBuilder sb = new StringBuilder();
using(FileStream aStream = new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
StreamReader aReader = new StreamReader(aStream, Encoding.UTF8);
aReader.BaseStream.Seek(0, SeekOrigin.Begin);
string streamLine = aReader.ReadLine();
while (streamLine != null)
{
if (streamLine.Contains(@"javascript.enabled") && streamLine.Contains("false"))
{
streamLine = streamLine.Replace("false", "true");
}
sb.Append(streamLine + "\r\n");
streamLine = aReader.ReadLine();
}
//writeLine = sb.ToString().Split("\r\n".ToCharArray());
aReader.Close();
}
File.Delete(filePath);
AddToFile(filePath, sb.ToString());
}
/// <summary>
/// Delete one line which contains the "javaScript.enabled.
/// </summary>
/// <param name="filePath">the path of js file.</param>
public static void DisableFFJaveScript(string filePath)
{
StringBuilder sb = new StringBuilder();
using (FileStream aStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
StreamReader aReader = new StreamReader(aStream, Encoding.UTF8);
StreamWriter aWriter = new StreamWriter(aStream, Encoding.UTF8);
aReader.BaseStream.Seek(0, SeekOrigin.Begin);
string streamLine = aReader.ReadLine();
bool isJSDisabled = false;
bool isJSFalse = false;
while (streamLine != null)
{
if (streamLine.Contains("javascript.enable") && streamLine.Contains("false"))
{
isJSFalse = true;
}
if (streamLine.Contains("javascript.enable") && streamLine.Contains("true"))
{
streamLine = streamLine.Replace("true", "false");
isJSDisabled = true;
}
sb.Append(streamLine + "\r\n");
streamLine = aReader.ReadLine();
}
if (!isJSDisabled && !isJSFalse)
sb.Append("user_pref(" + "\"javascript.enabled\"" + "," + " false);");
aReader.Close();
}
File.Delete(filePath);
AddToFile(filePath, sb.ToString());
}
/// <summary>
/// Add some stirng to a file.
/// </summary>
/// <param name="filePath">the path of the file</param>
/// <param name="writeLine">the content of on string.</param>
public static void AddToFile(string filePath, string writeLine)
{
using (FileStream aStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter aWriter = new StreamWriter(aStream, Encoding.UTF8))
{
aWriter.Flush();
aWriter.BaseStream.Seek(0, SeekOrigin.Begin);
aWriter.Write(writeLine);
aWriter.Flush();
}
}
}
/// <summary>
/// Delete one line of file contains user_pref(,true/false)
/// </summary>
/// <param name="aStream"></param>
public static void DeleteLineFile(FileStream aStream,string filePath)
{
string streamLine = string.Empty;
StreamReader aReader = new StreamReader(aStream, Encoding.UTF8);
aReader.BaseStream.Seek(0, SeekOrigin.Begin);
string[] streamAll = aReader.ReadToEnd().Split("\r\n".ToCharArray());
List<string> aString = new List<string>();
foreach (string aLine in streamAll)
{
if (!aLine.Contains(@"javascript.enable"))
{
aString.Add(aLine);
}
}
aReader.Close();
aStream.Close();
File.Delete(filePath);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter aWriter = new StreamWriter(fs, Encoding.UTF8))
{
aWriter.BaseStream.Seek(0, SeekOrigin.Begin);
foreach (string aLine in aString)
{
aWriter.WriteLine(aLine);
}
}
}
}
/// <summary>
/// Read derictly from the XML file with some configs.
/// That means users have to reconfig the XML node then can continue the test.
/// </summary>
/// <returns></returns>
public static string GetUserFilePathByXMLWithConfig()
{
string filePath = string.Empty;
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
string[] userName = currentUser.Split(@"\".ToCharArray());
currentUser = userName[userName.Length - 1];
StringBuilder sb = new StringBuilder();
string xmlFileName = @"filePath.xml";
XmlDocument aDoc = new XmlDocument();
aDoc.Load(xmlFileName);
XmlNode aNode = aDoc.SelectSingleNode("filePaths");
return aNode.SelectSingleNode("filePath").InnerText;
}
/// <summary>
/// Read derictly from the XML file without any other configuration.
/// The system infomation which contains the User Alias.
/// </summary>
/// <returns></returns>
public static string GetUserFilePathByXMLWithoutConfig()
{
string filePath = string.Empty;
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
string[] userName = currentUser.Split(@"\".ToCharArray());
currentUser = userName[userName.Length - 1];
StringBuilder sb = new StringBuilder();
string xmlFileName = @"filePath.xml";
XmlDocument aDoc = new XmlDocument();
aDoc.Load(xmlFileName);
XmlNode aNode = aDoc.SelectSingleNode("filePaths");
sb.Append(aNode.SelectSingleNode("filePathPartial1").InnerText);
sb.Append(currentUser);
sb.Append(aNode.SelectSingleNode("filePathPartial2").InnerText);
return sb.ToString();
}
/// <summary>
/// Get Current Script state of IE.
/// </summary>
/// <param name="regPath"></param>
/// <returns>true ---> allow Script.</returns>
public static bool GetIECurrentScriptState(string regPath)
{
bool ret = false;
RegistryKey regSubkey = null;
regSubkey = Registry.CurrentUser.OpenSubKey(regPath, true);
if (regSubkey.GetValue("1400").ToString() == "0")
{
ret = true;
}
if ((int)regSubkey.GetValue("1400") == 3)
{
ret = false;
}
return ret;
}
/// <summary>
/// Get the current cookies state of IE.
/// </summary>
/// <param name="regPath">the registry of internet zone.</param>
/// <returns>true--->allow all cookies.</returns>
public static bool GetIECurrentCookiesState(string regPath)
{
bool ret = false;
RegistryKey regSubKey = null;
regSubKey = Registry.CurrentUser.OpenSubKey(regPath, true);
if ((int)regSubKey.GetValue("1A02") == 0)
{
ret = true;
}
if ((int)regSubKey.GetValue("1A02") == 3)
{
ret = false;
}
return ret;
}
}
}

後文:

有人就會問了,用鼠標隨便點點就能夠輕松實現的東西,為什麼還有寫這麼多亂七八糟的代碼呢?

我認為有幾點好處:

1.本例更適合使用在測試代碼中,通過此,可以計算開發代碼的code coverage

2.手工要比自動化效率低下,款且存在很大的誤差。

3.開發人員也可以此檢測當前用戶狀態,以改變不同的現實效果或者提示。

目前只是發現了FF和IE的操作,並且對IE8的注冊表修改還是有小小的不同。對於其他眾多浏覽器,大家有研究的可以給我提供些新鮮的信息和想法。一起交流學習,有疏漏的地方大家補充。

出處:http://alexliu.cnblogs.com/

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved