【问题标题】:How can I overwrite the btnSubmit_onclick javascript function on a web page using the WPF WebBrowser?如何使用 WPF WebBrowser 覆盖网页上的 btnSubmit_onclick javascript 函数?
【发布时间】:2010-10-10 05:05:17
【问题描述】:

我正在使用与 WinForms 版本不同的 WPF WebBrowser 控件,并且这个优秀网站的许多建议在 WPF 中根本不起作用。

如何覆盖网页上的btnSubmit_onclick() javascript 函数?

这个函数会生成一个我想绕过的确认对话框(比如“你确定吗?”)。基本上我想注入一个新函数btnSubmit_onclick(),它将替换现有的函数,我可以省略烦人的确认对话框。我可以访问 MSHTML 和所有页面对象,但很难在页面标题处注入脚本。到目前为止,我得到了:

mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)webBrowser.Document;
mshtml.IHTMLElementCollection heads = doc.all.tags("head") as mshtml.IHTMLElementCollection;
mshtml.IHTMLElement head = heads.item(null, 0) as mshtml.IHTMLElement;
mshtml.IHTMLElement se = doc.createElement("script") as mshtml.IHTMLElement;
se.innerHTML = "function btnSubmit_onclick() { alert('here we are'); }";

但是现在我需要先将这个新的脚本元素注入到头部对象中,然后再注入其他脚本,我希望它会覆盖下游现有的btnSubmit_onclick() 函数。

我没有成功尝试 head.injectAdjusentHTML,即使我使用 DEFER 属性,它也拒绝将任何脚本注入到标题中。

我该怎么做?

【问题讨论】:

    标签: javascript wpf browser mshtml overwrite


    【解决方案1】:

    我认为您需要将它添加到头部的末尾,而不是在其他之前注入它。我相信 javascript 是一种最后一胜的交易。

    【讨论】:

      【解决方案2】:

      我没有测试过,只是一个猜测: 试试这个:

      // For this code to work: add the Microsoft.mshtml .NET reference
      mshtml.IHTMLDocument2 doc = WebBrowser1.Document as mshtml.IHTMLDocument2;
      doc.parentWindow.execScript("document.body.onsubmit=new function(){ alert('here we are'); };");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-06
        • 2011-07-21
        • 2010-12-04
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        相关资源
        最近更新 更多