How can I overwrite the btnSubmit_onclick javascri

2019-08-17 05:38发布

I'm working with the WPF WebBrowser control which is different from the WinForms version and many recommendations from this excellent web site simply do not work in WPF.

How can I overwrite the btnSubmit_onclick() javascript function on a web page?

This function generates a confirm dialog (like "Are you sure?") which I want to bypass. Basically I want to inject a new function btnSubmit_onclick() which will replace the existing one and I can omit annoying confirm dialog. I have access to MSHTML and all page objects, but struggle to inject script at the header of the page. So far I've got:

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'); }";

But now I need to inject this new script element into head object before other the other scripts, and I hope it will owerwrite existing btnSubmit_onclick() function downstream.

I unsuccessfully tried head.injectAdjusentHTML which refuses to inject any script into the header even I use DEFER property.

How can i do it?

2条回答
我想做一个坏孩纸
2楼-- · 2019-08-17 06:02

I havent tested this, is just a guess: Try this:

// 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'); };");
查看更多
走好不送
3楼-- · 2019-08-17 06:10

I think you need to add it to the end of the head instead of inject it before the others. I believe javascript is a last-one-wins type of deal.

查看更多
登录 后发表回答