承上篇,本文提供修改 IE 登錄與 Firefox prefs.js 的完整程式碼,實現程式化切換 JavaScript 啟用/停用。
IE 安全區域設定儲存於 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\。鍵值 1400 (Active Scripting):0 = 啟用,3 = 停用。
public static bool GetIECurrentScriptState(string zonePath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3")
{
using (var key = Registry.CurrentUser.OpenSubKey(zonePath, true))
{
var val = key?.GetValue("1400");
return val != null && (int)val == 0; // 0=啟用, 3=停用
}
}
public static void SetIEScriptEnabled(bool enabled, string zonePath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3")
{
using (var key = Registry.CurrentUser.OpenSubKey(zonePath, true))
{
key?.SetValue("1400", enabled ? 0 : 3, RegistryValueKind.DWord);
}
// 通知 IE 重新讀取設定 (可選)
InternetSetOption(IntPtr.Zero, 39, IntPtr.Zero, 0); // INTERNET_OPTION_SETTINGS_CHANGED
}
[DllImport("wininet.dll")] static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
Firefox 設定儲存於設定檔目錄下的 prefs.js:user_pref("javascript.enabled", true/false);。設定檔目錄名稱含隨機字串 (如 xxxxxxxx.default),需動態查找。
public static string FindFirefoxPrefsJs()
{
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string profilesDir = Path.Combine(appData, "Mozilla", "Firefox", "Profiles");
if (!Directory.Exists(profilesDir)) return null;
foreach (var dir in Directory.GetDirectories(profilesDir))
{
string prefs = Path.Combine(dir, "prefs.js");
if (File.Exists(prefs)) return prefs;
}
return null;
}
public static void SetFirefoxScriptEnabled(bool enabled)
{
string prefsPath = FindFirefoxPrefsJs();
if (prefsPath == null) throw new FileNotFoundException("找不到 Firefox prefs.js");
var lines = File.ReadAllLines(prefsPath, Encoding.UTF8);
bool found = false;
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("javascript.enabled"))
{
lines[i] = $'user_pref("javascript.enabled", {enabled.ToString().ToLower()});';
found = true;
break;
}
}
if (!found)
Array.Resize(ref lines, lines.Length + 1);
lines[^1] = $'user_pref("javascript.enabled", {enabled.ToString().ToLower()});';
File.WriteAllLines(prefsPath, lines, Encoding.UTF8);
}
prefs.js 時 Firefox 不能執行,否則啟動時會覆寫回原值。profiles.ini 中的預設設定檔。若目標為自動化測試/爬蟲,建議直接使用 Selenium WebDriver / Playwright / Puppeteer Sharp 等瀏覽器自動化框架,它們提供原生 API 控制 JavaScript 啟用狀態,無需修改系統設定,且支援無頭模式、跨平台。