How can I overwrite the btnSubmit_onclick javascript function on a web page using the WPF WebBrowser?

岁酱吖の 提交于 2019-12-11 15:39:26

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/592688/how-can-i-overwrite-the-btnsubmit-onclick-javascript-function-on-a-web-page-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!