这两天一直研究如何通过代码来实现对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 安全区域注册表项说明中有一部分提到的如下的内容,那么我们就可以通过修改注册表中的选项来达到我们预期的要求。
Code
/// <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中注册表的改变:
Code
/// <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,状态的读取,改变。
有一切问题都欢迎拍砖:)
Code
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的注册表修改还是有小小的不同。对于其他众多浏览器,大家有研究的可以给我提供些新鲜的信息和想法。一起交流学习,有疏漏的地方大家补充。