gpt4 book ai didi

javascript - 如何使用 webbrowser 控件将 javascript 注入(inject) iframe?

转载 作者:行者123 更新时间:2023-11-30 00:22:14 25 4
gpt4 key购买 nike

我试图阻止某些向用户显示警报的 javascript 函数。

我目前正在使用这段代码,但它不起作用:

    private void InjectAlertBlocker()
{
string alertBlocker = @"window.alert = function () { };
window.print = function () { };
window.open = function () { };
window.onunload = function () { };
window.prompt = function () { };
window.confirm = function() { };
window.onbeforeunload = function () { };";

wb.Document.InvokeScript("execScript", new Object[] { alertBlocker, "JavaScript" });
}

Web 浏览器控件在后台运行,一些需要访问的站点显示随机弹出给用户的警报。

我尝试过类似的代码,但无法使它们中的任何一个正常工作。

更新:

经过一些检查,这段代码似乎确实阻止了警报。但是,在我的特定情况下,警报来自 iframe,这就是我的代码没有阻止它的原因。w3schools 上的 javascript 警报示例是一个完美的示例:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert

如何覆盖 iframe 中的脚本?

更新 2:

我尝试将 javascript 代码(由 Buzinas 在他的回答中提供)注入(inject)主页,这将遍历所有 iframe 并覆盖它们的警报功能,但由于同源,它大部分时间都会导致错误政策。

最佳答案

无需调用脚本,您可以将其附加为 <script>元素:

HtmlElement head = wb.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = wb.Document.CreateElement("script");
IHTMLScriptElement el = (IHTMLScriptElement)scriptEl.DomElement;
el.text = @"window.alert = function () { };
window.print = function () { };
window.open = function () { };
window.onunload = function () { };
window.onbeforeunload = function () { };";
head.AppendChild(scriptEl);

更新

要确保所有 iframe 都被阻止,您可以这样做:

HtmlElement head = wb.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = wb.Document.CreateElement("script");
IHTMLScriptElement el = (IHTMLScriptElement)scriptEl.DomElement;
el.text = @"window.alert = function () { };
window.print = function () { };
window.open = function () { };
window.onunload = function () { };
window.onbeforeunload = function () { };

var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; i++) {
var win = iframes[i].contentWindow;
win.alert = function () { };
win.print = function () { };
win.open = function () { };
win.onunload = function () { };
win.onbeforeunload = function () { };
}";
head.AppendChild(scriptEl);

关于javascript - 如何使用 webbrowser 控件将 javascript 注入(inject) iframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32719826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com