C# .NET WebBrowser控件-覆盖IFrame的脚本?
在卸载Windows.Form.WebBrowser控件浏览的任何网站之前,我想挂起/禁用window.alert和window.on。在主站点上调用这些函数时,我成功地重写了它们,但如果在Iframe上调用它们,我仍然无法重写此函数 为了重现这个案例,我制作了两个HTML文件C# .NET WebBrowser控件-覆盖IFrame的脚本?,c#,javascript,iframe,inject,C#,Javascript,Iframe,Inject,在卸载Windows.Form.WebBrowser控件浏览的任何网站之前,我想挂起/禁用window.alert和window.on。在主站点上调用这些函数时,我成功地重写了它们,但如果在Iframe上调用它们,我仍然无法重写此函数 为了重现这个案例,我制作了两个HTML文件 测试HTML文件:主站点和远程站点 主要地点: <html> <head> <script> window.onbeforeunload = confirmExit;
<html>
<head>
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "Onbeforeunload from main";
}
alert("Alert from main")
</script>
</head>
<body>
<a href="http://google.com">Google</a>
<iframe src="remote.html">
</body>
</html>
代码:
private void webBrowser1\u已导航(对象发送方,WebBrowserNavigatedEventArgs e)
{
ExecuteMe();
}
私有无效webBrowser1_ProgressChanged(对象发送方,WebBrowserProgressChangedEventArgs e)
{
ExecuteMe();
}
私有void ExecuteMe()
{
DisableAlertIE(webBrowser1.Document作为HtmlDocument);
HtmlDocument document=(webBrowser1.document作为HtmlDocument);
如果(文档!=null)
{
for(int index=0;index
当我让程序运行时,主站点的window.alert和window.onbeforeunload已成功挂起,但远程站点的alert和onbeforeunload仍被调用
问题:我应该如何改进代码以在卸载远程站点之前挂起警报和OnForeUnload
<html>
<head>
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "Onbeforeunload from remote";
}
alert("Alert from remote")
</script>
</head>
<body>
<a href="http://google.com">Google</a>
</body>
</html>
webBrowser1.Navigate(@"file://127.0.0.1/C$/Users/ServusKevin/Desktop/main.html");
webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
webBrowser1.ProgressChanged += new WebBrowserProgressChangedEventHandler(webBrowser1_ProgressChanged);
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
ExecuteMe();
}
private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
ExecuteMe();
}
private void ExecuteMe()
{
DisableAlertIE(webBrowser1.Document as HtmlDocument);
HtmlDocument document = (webBrowser1.Document as HtmlDocument);
if (document != null)
{
for (int index = 0; index < document.Window.Frames.Count; index++)
{
try
{
DisableAlertIE((document.Window.Frames[index]).Document);
}
catch
{
}
}
}
}
private void DisableAlertIE(HtmlDocument document)
{
if (document != null)
{
//HTMLDocument document = wbIE.Document as HTMLDocument;
HtmlElement scriptSuppressed = document.CreateElement("script");
IHTMLScriptElement scriptDomElement = (IHTMLScriptElement)scriptSuppressed.DomElement;
scriptDomElement.type = "text/javascript";
scriptDomElement.text = @"window.alert = function () { }; window.confirm = function () { }; window.prompt = function () { }; window.print = function () { }; window.onbeforeunload = function () {};";
foreach (HtmlElement head in document.GetElementsByTagName("head"))
{
head.AppendChild(scriptSuppressed);
}
}
}