Recently in a client program, using the WebBrowser control, when JS call window.open () or a tag target= "_blank" when using the pop-up IE window, do not know why this design, simply do not meet the needs of it. On the Internet to check the relevant information, found that the control does not have properties to control this function, so find a third-party control, it is still not able to find (perhaps I am not careful to try), but also a few more than 10 megabytes of the DLL. After a few hours of my efforts, gave up ...!
Know that C # is able to interact with the Web page JS, so think of the page rewrite window.open () method, build an HTML page to try, confirm the JS rewrite window.open (), JS code:
Window.open=function (URL) {window.location.href=url;}
Trial run, the success was rewritten.
Since I cannot change the Web page, I refer to C # WebBrowser the method of executing the JS code:
IHTMLDocument2 doc2 = (IHTMLDocument2) webbrowser1.document.domdocument;doc2.parentwindow.execscript ("window.open= function (URL) {window.location.href=url;} ");
????? all OK, but there is a problem, is this method used to IHTMLDocument2, need to reference Microsoft.mshtml.dll, this DLL is self-brought, the location is generally in C:\Program files\ Microsoft.net\primary Interop assemblies, nearly 8M, I certainly can not endure ah, so continue on this road farther and deeper. ?
after using a method that does not need to refer to an external DLL, it is possible to use HTMLDocument directly: ?
HTMLDocument doc = webbrowser1.document; HtmlElement script = doc. createelement ("script"); script. SetAttribute ("type", "Text/javascript"); script. SetAttribute ("text", "window.open=function (URL) {window.location.href=url;}"); Doc. Body.appendchild (script);
Of course you also will JS can be written method, and then use Doc.invokescript () call, here I don't care.
Then there is a problem, this code in the current document is valid, that is, the HTML inside the iframe contains HTML does not take effect, resolved:
The above doc is changed to: Doc = webbrowser1.document.window.frames["iframe name"]. Document;
It would be nice if multiple iframe words were traversed.
Finally the target of a tag to change it, and finally finished, here to share a record ~
Reproduced please respect the original, OK?
The VS C #. NET WebBrowser control uses the Insert JS code to implement control pop-up IE window