refactor: 重构浏览器功能并添加Cookie支持
重构了浏览器功能,删除了旧的Form1窗体,新增了Browser窗体以支持带Cookie的网页浏览。同时添加了.gitignore文件和解决方案文件,优化了项目结构。
This commit is contained in:
parent
9c4b983693
commit
ac817d1c7b
83
.gitignore
vendored
Normal file
83
.gitignore
vendored
Normal file
@ -0,0 +1,83 @@
|
||||
/.github
|
||||
/.idea
|
||||
/.vs
|
||||
/.vscode
|
||||
|
||||
#环境变量
|
||||
.env
|
||||
|
||||
#构建删除
|
||||
Run/*.exe
|
||||
|
||||
# 忽略所有obj
|
||||
**/obj/**
|
||||
|
||||
# 已构建程序不上传
|
||||
*.exe
|
||||
|
||||
# IDEA
|
||||
Server/.idea
|
||||
|
||||
[Tt]humbs.db
|
||||
*.DS_Store
|
||||
|
||||
#Visual Studio files
|
||||
*.[Oo]bj
|
||||
*.user
|
||||
*.aps
|
||||
*.pch
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
*_i.c
|
||||
*_p.c
|
||||
*.ncb
|
||||
*.suo
|
||||
*.tlb
|
||||
*.tlh
|
||||
*.bak
|
||||
*.[Cc]ache
|
||||
*.ilk
|
||||
*.log
|
||||
*.lib
|
||||
*.sbr
|
||||
*.sdf
|
||||
*.opensdf
|
||||
*.unsuccessfulbuild
|
||||
ipch/
|
||||
obj/
|
||||
[Bb]in
|
||||
[Dd]ebug*/
|
||||
[Rr]elease*/
|
||||
Ankh.NoLoad
|
||||
|
||||
#MonoDevelop
|
||||
*.pidb
|
||||
*.userprefs
|
||||
|
||||
#Tooling
|
||||
_ReSharper*/
|
||||
*.resharper
|
||||
[Tt]est[Rr]esult*
|
||||
*.sass-cache
|
||||
|
||||
#Project files
|
||||
[Bb]uild/
|
||||
|
||||
#Subversion files
|
||||
.svn
|
||||
|
||||
# Office Temp Files
|
||||
~$*
|
||||
|
||||
#NuGet
|
||||
packages/
|
||||
|
||||
#ncrunch
|
||||
*ncrunch*
|
||||
*crunch*.local.xml
|
||||
|
||||
# visual studio database projects
|
||||
*.dbmdl
|
||||
|
||||
#Test files
|
||||
*.testsettings
|
@ -1,9 +1,9 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.13.35931.197 d17.13
|
||||
VisualStudioVersion = 17.13.35931.197
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FromBrowser", "FromBrowser\FromBrowser.csproj", "{88D34179-7D4E-42B1-A755-CA96F7B242B4}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FormBrowser", "FromBrowser\FormBrowser.csproj", "{88D34179-7D4E-42B1-A755-CA96F7B242B4}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
1
FromBrowser/.vs/FromBrowser.csproj.dtbcache.json
Normal file
1
FromBrowser/.vs/FromBrowser.csproj.dtbcache.json
Normal file
@ -0,0 +1 @@
|
||||
{"RootPath":"C:\\Git\\FromBrowser\\FromBrowser","ProjectFileName":"FromBrowser.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[{"SourceFile":"Form1.cs"},{"SourceFile":"Form1.Designer.cs"},{"SourceFile":"Program.cs"},{"SourceFile":"Properties\\AssemblyInfo.cs"},{"SourceFile":"Properties\\Resources.Designer.cs"},{"SourceFile":"Properties\\Settings.Designer.cs"},{"SourceFile":"obj\\Debug\\.NETFramework,Version=v4.7.2.AssemblyAttributes.cs"}],"References":[{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\Microsoft.CSharp.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\mscorlib.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Core.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Data.DataSetExtensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Data.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Deployment.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Drawing.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Net.Http.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Windows.Forms.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Xml.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.7.2\\System.Xml.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""}],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Git\\FromBrowser\\FromBrowser\\bin\\Debug\\FromBrowser.exe","OutputItemRelativePath":"FromBrowser.exe"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]}
|
146
FromBrowser/Browser.Designer.cs
generated
Normal file
146
FromBrowser/Browser.Designer.cs
generated
Normal file
@ -0,0 +1,146 @@
|
||||
namespace FormBrowser
|
||||
{
|
||||
partial class Browser
|
||||
{
|
||||
/// <summary>
|
||||
/// 必需的设计器变量。
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
private System.Windows.Forms.TextBox txtUrl;
|
||||
private System.Windows.Forms.Button btnGo;
|
||||
private System.Windows.Forms.Button btnBack;
|
||||
private System.Windows.Forms.Button btnForward;
|
||||
private System.Windows.Forms.Button btnRefresh;
|
||||
private System.Windows.Forms.Panel navPanel;
|
||||
|
||||
/// <summary>
|
||||
/// 清理所有正在使用的资源。
|
||||
/// </summary>
|
||||
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Windows 窗体设计器生成的代码
|
||||
|
||||
/// <summary>
|
||||
/// 设计器支持所需的方法 - 不要修改
|
||||
/// 使用代码编辑器修改此方法的内容。
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this.webBrowser1 = new System.Windows.Forms.WebBrowser();
|
||||
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
|
||||
this.navPanel = new System.Windows.Forms.Panel();
|
||||
this.btnBack = new System.Windows.Forms.Button();
|
||||
this.btnForward = new System.Windows.Forms.Button();
|
||||
this.btnRefresh = new System.Windows.Forms.Button();
|
||||
this.txtUrl = new System.Windows.Forms.TextBox();
|
||||
this.btnGo = new System.Windows.Forms.Button();
|
||||
this.navPanel.SuspendLayout();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// webBrowser1
|
||||
//
|
||||
this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
|
||||
this.webBrowser1.Location = new System.Drawing.Point(0, 40);
|
||||
this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
|
||||
this.webBrowser1.Name = "webBrowser1";
|
||||
this.webBrowser1.ScriptErrorsSuppressed = true;
|
||||
this.webBrowser1.Size = new System.Drawing.Size(1024, 728);
|
||||
this.webBrowser1.TabIndex = 0;
|
||||
this.webBrowser1.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.WebBrowser_Navigated);
|
||||
//
|
||||
// navPanel
|
||||
//
|
||||
this.navPanel.Controls.Add(this.btnBack);
|
||||
this.navPanel.Controls.Add(this.btnForward);
|
||||
this.navPanel.Controls.Add(this.btnRefresh);
|
||||
this.navPanel.Controls.Add(this.txtUrl);
|
||||
this.navPanel.Controls.Add(this.btnGo);
|
||||
this.navPanel.Dock = System.Windows.Forms.DockStyle.Top;
|
||||
this.navPanel.Location = new System.Drawing.Point(0, 0);
|
||||
this.navPanel.Name = "navPanel";
|
||||
this.navPanel.Size = new System.Drawing.Size(1024, 40);
|
||||
this.navPanel.TabIndex = 1;
|
||||
//
|
||||
// btnBack
|
||||
//
|
||||
this.btnBack.Location = new System.Drawing.Point(5, 5);
|
||||
this.btnBack.Name = "btnBack";
|
||||
this.btnBack.Size = new System.Drawing.Size(60, 30);
|
||||
this.btnBack.TabIndex = 0;
|
||||
this.btnBack.Text = "后退";
|
||||
this.btnBack.UseVisualStyleBackColor = true;
|
||||
this.btnBack.Click += new System.EventHandler(this.BtnBack_Click);
|
||||
//
|
||||
// btnForward
|
||||
//
|
||||
this.btnForward.Location = new System.Drawing.Point(70, 5);
|
||||
this.btnForward.Name = "btnForward";
|
||||
this.btnForward.Size = new System.Drawing.Size(60, 30);
|
||||
this.btnForward.TabIndex = 1;
|
||||
this.btnForward.Text = "前进";
|
||||
this.btnForward.UseVisualStyleBackColor = true;
|
||||
this.btnForward.Click += new System.EventHandler(this.BtnForward_Click);
|
||||
//
|
||||
// btnRefresh
|
||||
//
|
||||
this.btnRefresh.Location = new System.Drawing.Point(135, 5);
|
||||
this.btnRefresh.Name = "btnRefresh";
|
||||
this.btnRefresh.Size = new System.Drawing.Size(60, 30);
|
||||
this.btnRefresh.TabIndex = 2;
|
||||
this.btnRefresh.Text = "刷新";
|
||||
this.btnRefresh.UseVisualStyleBackColor = true;
|
||||
this.btnRefresh.Click += new System.EventHandler(this.BtnRefresh_Click);
|
||||
//
|
||||
// txtUrl
|
||||
//
|
||||
this.txtUrl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
|
||||
| System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.txtUrl.Location = new System.Drawing.Point(199, 9);
|
||||
this.txtUrl.Name = "txtUrl";
|
||||
this.txtUrl.Size = new System.Drawing.Size(700, 21);
|
||||
this.txtUrl.TabIndex = 3;
|
||||
this.txtUrl.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TxtUrl_KeyDown);
|
||||
//
|
||||
// btnGo
|
||||
//
|
||||
this.btnGo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.btnGo.Location = new System.Drawing.Point(905, 5);
|
||||
this.btnGo.Name = "btnGo";
|
||||
this.btnGo.Size = new System.Drawing.Size(60, 30);
|
||||
this.btnGo.TabIndex = 4;
|
||||
this.btnGo.Text = "转到";
|
||||
this.btnGo.UseVisualStyleBackColor = true;
|
||||
this.btnGo.Click += new System.EventHandler(this.BtnGo_Click);
|
||||
//
|
||||
// Browser
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(1024, 768);
|
||||
this.Controls.Add(this.webBrowser1);
|
||||
this.Controls.Add(this.navPanel);
|
||||
this.Name = "Browser";
|
||||
this.Text = "Cookie浏览器";
|
||||
this.Load += new System.EventHandler(this.Browser_Load);
|
||||
this.navPanel.ResumeLayout(false);
|
||||
this.navPanel.PerformLayout();
|
||||
this.ResumeLayout(false);
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private System.Windows.Forms.WebBrowser webBrowser1;
|
||||
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
|
||||
}
|
||||
}
|
||||
|
474
FromBrowser/Browser.cs
Normal file
474
FromBrowser/Browser.cs
Normal file
@ -0,0 +1,474 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using System.Net;
|
||||
using System.IO;
|
||||
|
||||
namespace FormBrowser
|
||||
{
|
||||
public partial class Browser : Form
|
||||
{
|
||||
private string currentCookies;
|
||||
|
||||
public Browser()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用指定的URL和Cookie创建浏览器窗口
|
||||
/// </summary>
|
||||
/// <param name="url">要访问的网址</param>
|
||||
/// <param name="cookies">Cookie字符串,格式为"name1=value1; name2=value2"</param>
|
||||
public Browser(string url, string cookies) : this()
|
||||
{
|
||||
this.currentCookies = cookies;
|
||||
NavigateWithCookies(url, cookies);
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void Browser_Load(object sender, EventArgs e)
|
||||
{
|
||||
// 窗体加载时的初始化操作
|
||||
|
||||
// 设置WebBrowser使用最新的IE版本
|
||||
SetBrowserFeatureControl();
|
||||
|
||||
// 设置Grafana特定配置
|
||||
ConfigureForGrafana();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置浏览器以更好地支持Grafana
|
||||
/// </summary>
|
||||
private void ConfigureForGrafana()
|
||||
{
|
||||
// 设置WebBrowser的脚本错误抑制
|
||||
webBrowser1.ScriptErrorsSuppressed = true;
|
||||
|
||||
// 设置额外的浏览器特性控制,以支持现代Web应用
|
||||
string appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
|
||||
|
||||
// 启用JavaScript
|
||||
SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", appName, 11001); // IE11 Edge模式
|
||||
SetBrowserFeatureControlKey("FEATURE_AJAX_CONNECTIONEVENTS", appName, 1);
|
||||
SetBrowserFeatureControlKey("FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION", appName, 1);
|
||||
SetBrowserFeatureControlKey("FEATURE_MANAGE_SCRIPT_CIRCULAR_REFS", appName, 1);
|
||||
SetBrowserFeatureControlKey("FEATURE_DOMSTORAGE ", appName, 1);
|
||||
SetBrowserFeatureControlKey("FEATURE_GPU_RENDERING ", appName, 1);
|
||||
SetBrowserFeatureControlKey("FEATURE_WEBOC_DOCUMENT_ZOOM", appName, 1);
|
||||
SetBrowserFeatureControlKey("FEATURE_NINPUT_LEGACYMODE", appName, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置WebBrowser控件使用最新的IE版本
|
||||
/// </summary>
|
||||
private void SetBrowserFeatureControl()
|
||||
{
|
||||
// 获取当前应用程序名称
|
||||
string appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
|
||||
|
||||
// 设置IE特性控制
|
||||
SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION", appName, GetBrowserEmulationMode());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取浏览器模拟模式值
|
||||
/// </summary>
|
||||
/// <returns>IE版本对应的值</returns>
|
||||
private uint GetBrowserEmulationMode()
|
||||
{
|
||||
// 返回IE11的模拟模式值 (11001表示IE11 Edge模式)
|
||||
return 11001;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置浏览器特性控制注册表项
|
||||
/// </summary>
|
||||
/// <param name="featureName">特性名称</param>
|
||||
/// <param name="appName">应用程序名称</param>
|
||||
/// <param name="value">设置的值</param>
|
||||
private void SetBrowserFeatureControlKey(string featureName, string appName, uint value)
|
||||
{
|
||||
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
|
||||
@"Software\Microsoft\Internet Explorer\Main\FeatureControl\" + featureName, Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree))
|
||||
{
|
||||
key.SetValue(appName, value, Microsoft.Win32.RegistryValueKind.DWord);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用Cookie导航到指定URL
|
||||
/// </summary>
|
||||
/// <param name="url">要访问的网址</param>
|
||||
/// <param name="cookies">Cookie字符串</param>
|
||||
public void NavigateWithCookies(string url, string cookies)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
return;
|
||||
|
||||
// 保存当前Cookie
|
||||
this.currentCookies = cookies;
|
||||
|
||||
// 设置地址栏文本
|
||||
txtUrl.Text = url;
|
||||
|
||||
try
|
||||
{
|
||||
// 创建Cookie容器并添加Cookie
|
||||
CookieContainer cookieContainer = new CookieContainer();
|
||||
|
||||
// 解析URL获取域名
|
||||
Uri uri = new Uri(url);
|
||||
string domain = uri.Host;
|
||||
|
||||
// 解析Cookie字符串并添加到容器
|
||||
if (!string.IsNullOrEmpty(cookies))
|
||||
{
|
||||
string[] cookiePairs = cookies.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string cookiePair in cookiePairs)
|
||||
{
|
||||
string[] cookieNameValue = cookiePair.Trim().Split(new[] { '=' }, 2);
|
||||
if (cookieNameValue.Length == 2)
|
||||
{
|
||||
string name = cookieNameValue[0].Trim();
|
||||
string value = cookieNameValue[1].Trim();
|
||||
Cookie cookie = new Cookie(name, value, "/", domain);
|
||||
cookieContainer.Add(cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建HTTP请求
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.CookieContainer = cookieContainer;
|
||||
request.Method = "GET";
|
||||
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67";
|
||||
|
||||
// 添加额外的HTTP头以模拟现代浏览器
|
||||
// 使用专用属性设置Accept标头,而不是Headers.Add
|
||||
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
|
||||
request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
|
||||
request.Headers.Add("Upgrade-Insecure-Requests", "1");
|
||||
request.Headers.Add("sec-ch-ua", "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Microsoft Edge\";v=\"114\"");
|
||||
request.Headers.Add("sec-ch-ua-mobile", "?0");
|
||||
request.Headers.Add("sec-ch-ua-platform", "\"Windows\"");
|
||||
|
||||
// 特别处理Grafana请求
|
||||
if (uri.Host.Contains("grafana") || url.Contains("/grafana"))
|
||||
{
|
||||
// 确保请求包含正确的Referer头
|
||||
string referer = $"{uri.Scheme}://{uri.Host}";
|
||||
if (!string.IsNullOrEmpty(uri.PathAndQuery))
|
||||
{
|
||||
// 如果URL包含子路径,确保Referer也包含
|
||||
string path = uri.AbsolutePath;
|
||||
if (path.EndsWith("/"))
|
||||
path = path.Substring(0, path.Length - 1);
|
||||
|
||||
// 如果是子路径下的Grafana,添加到Referer
|
||||
if (path.Contains("/"))
|
||||
{
|
||||
string subPath = path.Substring(0, path.LastIndexOf('/'));
|
||||
referer += subPath;
|
||||
}
|
||||
}
|
||||
request.Referer = referer;
|
||||
|
||||
// 添加额外的Grafana相关头信息
|
||||
request.Headers.Add("X-Grafana-Org-Id", "1");
|
||||
}
|
||||
|
||||
// 获取响应
|
||||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||||
{
|
||||
// 读取响应内容
|
||||
using (Stream stream = response.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
string html = reader.ReadToEnd();
|
||||
|
||||
// 处理Grafana的相对路径问题
|
||||
if (uri.Host.Contains("grafana") || url.Contains("/grafana"))
|
||||
{
|
||||
// 修复Grafana的相对路径引用
|
||||
string basePath = "";
|
||||
if (uri.AbsolutePath.Contains("/") && !uri.AbsolutePath.Equals("/"))
|
||||
{
|
||||
string path = uri.AbsolutePath;
|
||||
if (path.EndsWith("/"))
|
||||
path = path.Substring(0, path.Length - 1);
|
||||
|
||||
if (path.Contains("/"))
|
||||
basePath = path.Substring(0, path.LastIndexOf('/'));
|
||||
}
|
||||
|
||||
// 如果检测到Grafana加载失败的错误信息,尝试修复
|
||||
if (html.Contains("Grafana has failed to load its application files"))
|
||||
{
|
||||
// 在HTML中注入基础路径修复脚本
|
||||
html = html.Replace("</head>",
|
||||
$"<base href=\"{uri.Scheme}://{uri.Host}{basePath}/\">\n" +
|
||||
"<script>\n" +
|
||||
" // 修复Grafana资源加载路径\n" +
|
||||
" window.grafanaBootData = window.grafanaBootData || {{}}; \n" +
|
||||
$" window.grafanaBootData.settings = window.grafanaBootData.settings || {{}}; \n" +
|
||||
$" window.grafanaBootData.settings.appSubUrl = '{basePath}'; \n" +
|
||||
"</script>\n" +
|
||||
"</head>");
|
||||
}
|
||||
}
|
||||
|
||||
// 使用WebBrowser控件加载HTML内容前设置兼容性头信息
|
||||
string compatHtml = "<!DOCTYPE html>\n" +
|
||||
"<html>\n" +
|
||||
"<head>\n" +
|
||||
"<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n" +
|
||||
"</head>\n" +
|
||||
"<body>\n" +
|
||||
html +
|
||||
"\n</body>\n" +
|
||||
"</html>";
|
||||
|
||||
// 使用WebBrowser控件加载HTML内容
|
||||
webBrowser1.DocumentText = compatHtml;
|
||||
|
||||
// 设置文档URL,使相对链接正常工作
|
||||
webBrowser1.Url = uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"导航错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导航到指定URL
|
||||
/// </summary>
|
||||
/// <param name="url">要访问的网址</param>
|
||||
public void Navigate(string url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url))
|
||||
return;
|
||||
|
||||
// 处理Grafana URL,确保包含正确的子路径
|
||||
url = NormalizeGrafanaUrl(url);
|
||||
|
||||
// 如果有Cookie,使用Cookie导航
|
||||
if (!string.IsNullOrEmpty(currentCookies))
|
||||
{
|
||||
NavigateWithCookies(url, currentCookies);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 直接使用WebBrowser导航
|
||||
webBrowser1.Navigate(url);
|
||||
txtUrl.Text = url;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标准化Grafana URL,确保子路径正确
|
||||
/// </summary>
|
||||
/// <param name="url">原始URL</param>
|
||||
/// <returns>标准化后的URL</returns>
|
||||
private string NormalizeGrafanaUrl(string url)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 检查是否是Grafana URL
|
||||
if (url.Contains("grafana"))
|
||||
{
|
||||
Uri uri = new Uri(url);
|
||||
|
||||
// 如果URL不包含子路径,可能需要添加
|
||||
if (uri.AbsolutePath.Equals("/") || string.IsNullOrEmpty(uri.AbsolutePath))
|
||||
{
|
||||
// 检查URL中是否已经包含了查询参数
|
||||
string query = uri.Query;
|
||||
string baseUrl = url;
|
||||
|
||||
// 移除查询参数以便添加子路径
|
||||
if (!string.IsNullOrEmpty(query))
|
||||
{
|
||||
baseUrl = url.Replace(query, "");
|
||||
}
|
||||
|
||||
// 确保URL以/结尾,以便添加子路径
|
||||
if (!baseUrl.EndsWith("/"))
|
||||
{
|
||||
baseUrl += "/";
|
||||
}
|
||||
|
||||
// 重新组合URL,确保包含查询参数
|
||||
return baseUrl + (string.IsNullOrEmpty(query) ? "" : query);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"标准化Grafana URL时出错: {ex.Message}");
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
#region 事件处理方法
|
||||
|
||||
private void BtnBack_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (webBrowser1.CanGoBack)
|
||||
webBrowser1.GoBack();
|
||||
}
|
||||
|
||||
private void BtnForward_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (webBrowser1.CanGoForward)
|
||||
webBrowser1.GoForward();
|
||||
}
|
||||
|
||||
private void BtnRefresh_Click(object sender, EventArgs e)
|
||||
{
|
||||
webBrowser1.Refresh();
|
||||
}
|
||||
|
||||
private void BtnGo_Click(object sender, EventArgs e)
|
||||
{
|
||||
Navigate(txtUrl.Text);
|
||||
}
|
||||
|
||||
private void TxtUrl_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyCode == Keys.Enter)
|
||||
{
|
||||
Navigate(txtUrl.Text);
|
||||
e.SuppressKeyPress = true;
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void WebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
|
||||
{
|
||||
// 更新地址栏
|
||||
txtUrl.Text = webBrowser1.Url?.ToString() ?? string.Empty;
|
||||
|
||||
// 更新导航按钮状态
|
||||
btnBack.Enabled = webBrowser1.CanGoBack;
|
||||
btnForward.Enabled = webBrowser1.CanGoForward;
|
||||
|
||||
// 设置文档模式为Edge模式
|
||||
SetDocumentMode();
|
||||
|
||||
// 如果是Grafana页面,应用特殊处理
|
||||
string url = webBrowser1.Url?.ToString() ?? string.Empty;
|
||||
if (url.Contains("grafana"))
|
||||
{
|
||||
HandleGrafanaPage();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 处理Grafana页面的特殊需求
|
||||
/// </summary>
|
||||
private void HandleGrafanaPage()
|
||||
{
|
||||
if (webBrowser1.Document == null) return;
|
||||
|
||||
try
|
||||
{
|
||||
// 检查是否有Grafana加载失败的错误信息
|
||||
HtmlElement body = webBrowser1.Document.Body;
|
||||
if (body != null && body.InnerText.Contains("Grafana has failed to load its application files"))
|
||||
{
|
||||
// 获取当前URL信息
|
||||
Uri uri = webBrowser1.Url;
|
||||
if (uri == null) return;
|
||||
|
||||
// 确定基础路径
|
||||
string basePath = "";
|
||||
if (uri.AbsolutePath.Contains("/") && !uri.AbsolutePath.Equals("/"))
|
||||
{
|
||||
string path = uri.AbsolutePath;
|
||||
if (path.EndsWith("/"))
|
||||
path = path.Substring(0, path.Length - 1);
|
||||
|
||||
if (path.Contains("/"))
|
||||
basePath = path.Substring(0, path.LastIndexOf('/'));
|
||||
}
|
||||
|
||||
// 注入修复脚本
|
||||
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
|
||||
if (head != null)
|
||||
{
|
||||
// 添加base标签
|
||||
HtmlElement baseTag = webBrowser1.Document.CreateElement("base");
|
||||
baseTag.SetAttribute("href", $"{uri.Scheme}://{uri.Host}{basePath}/");
|
||||
head.AppendChild(baseTag);
|
||||
|
||||
// 添加修复脚本
|
||||
HtmlElement script = webBrowser1.Document.CreateElement("script");
|
||||
script.SetAttribute("type", "text/javascript");
|
||||
script.InnerHtml = $@"
|
||||
// 修复Grafana资源加载路径
|
||||
window.grafanaBootData = window.grafanaBootData || {{}};
|
||||
window.grafanaBootData.settings = window.grafanaBootData.settings || {{}};
|
||||
window.grafanaBootData.settings.appSubUrl = '{basePath}';
|
||||
";
|
||||
head.AppendChild(script);
|
||||
|
||||
// 刷新页面以应用更改
|
||||
webBrowser1.Refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"处理Grafana页面时出错: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置WebBrowser文档模式为Edge模式
|
||||
/// </summary>
|
||||
private void SetDocumentMode()
|
||||
{
|
||||
if (webBrowser1.Document != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 尝试通过执行JavaScript来设置文档模式
|
||||
webBrowser1.Document.InvokeScript("execScript", new object[]
|
||||
{
|
||||
"document.documentMode=11", "JavaScript"
|
||||
});
|
||||
|
||||
// 添加X-UA-Compatible元标记到文档头部
|
||||
dynamic head = webBrowser1.Document.GetElementsByTagName("head")[0];
|
||||
if (head != null)
|
||||
{
|
||||
dynamic meta = webBrowser1.Document.CreateElement("meta");
|
||||
meta.httpEquiv = "X-UA-Compatible";
|
||||
meta.content = "IE=edge";
|
||||
head.AppendChild(meta);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 忽略可能的脚本错误
|
||||
System.Diagnostics.Debug.WriteLine($"设置文档模式时出错: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
62
FromBrowser/Form1.Designer.cs
generated
62
FromBrowser/Form1.Designer.cs
generated
@ -1,62 +0,0 @@
|
||||
namespace FromBrowser
|
||||
{
|
||||
partial class Form1
|
||||
{
|
||||
/// <summary>
|
||||
/// 必需的设计器变量。
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// 清理所有正在使用的资源。
|
||||
/// </summary>
|
||||
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Windows 窗体设计器生成的代码
|
||||
|
||||
/// <summary>
|
||||
/// 设计器支持所需的方法 - 不要修改
|
||||
/// 使用代码编辑器修改此方法的内容。
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this.webBrowser1 = new System.Windows.Forms.WebBrowser();
|
||||
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// webBrowser1
|
||||
//
|
||||
this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
|
||||
this.webBrowser1.Location = new System.Drawing.Point(0, 0);
|
||||
this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
|
||||
this.webBrowser1.Name = "webBrowser1";
|
||||
this.webBrowser1.Size = new System.Drawing.Size(800, 450);
|
||||
this.webBrowser1.TabIndex = 0;
|
||||
//
|
||||
// Form1
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(800, 450);
|
||||
this.Controls.Add(this.webBrowser1);
|
||||
this.Name = "Form1";
|
||||
this.Text = "Form1";
|
||||
this.ResumeLayout(false);
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private System.Windows.Forms.WebBrowser webBrowser1;
|
||||
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
|
||||
}
|
||||
}
|
||||
|
@ -1,20 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace FromBrowser
|
||||
{
|
||||
public partial class Form1 : Form
|
||||
{
|
||||
public Form1()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
}
|
@ -46,14 +46,17 @@
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Form1.cs">
|
||||
<Compile Include="Browser.cs">
|
||||
<SubType>Form</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Form1.Designer.cs">
|
||||
<DependentUpon>Form1.cs</DependentUpon>
|
||||
<Compile Include="Browser.Designer.cs">
|
||||
<DependentUpon>Browser.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<EmbeddedResource Include="Browser.resx">
|
||||
<DependentUpon>Browser.cs</DependentUpon>
|
||||
</EmbeddedResource>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
@ -4,7 +4,7 @@ using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace FromBrowser
|
||||
namespace FormBrowser
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
@ -16,7 +16,12 @@ namespace FromBrowser
|
||||
{
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new Form1());
|
||||
|
||||
string url = "https://git.54sxh.cn/"; // 你要访问的网址
|
||||
string cookies = "gitea_incredible=JDsNY0PEJl%3Afa03bc6bc0f51c767cc876031280f08adb7030e8bc643b9916dc10150fa16858";
|
||||
|
||||
// 启动带Cookie的浏览器
|
||||
Application.Run(new Browser(url, cookies));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user