How to add a local script file to the HTML code of a WebBrowser control?

It seems really stupid. I tried a bunch of different ways and it just doesn't work. I have a WinForms application with a WebBrowser control. If I try with a raw html file on my desktop using the same src line, then the src that I put together works fine. But including the same element in a WebBrowser control will not work.

Here is my code:

HtmlElementCollection head = this.wbPreview.Document.GetElementsByTagName( "head" ); if (head != null) { HtmlElement elm = this.webBrowserControl.Document.CreateElement("script"); string mySource = Environment.CurrentDirectory + @"\MyScriptFile.js"; elm.SetAttribute("src", mySource); elm.SetAttribute("type", "text/javascript"); ((HtmlElement)head[0]).AppendChild(elm); } 

WebBrowser does not receive script. However, if I change mySource to an external resource (via http: //), it works great!

Help!

+11
javascript html c # webbrowser-control
Oct 27 '10 at 2:40
source share
4 answers

I went up to your post, playing with my work:

 HtmlElementCollection head = webBrowser1.Document.GetElementsByTagName("head"); if (head != null) { HtmlElement elm = webBrowser1.Document.CreateElement("script"); elm.SetAttribute("type", "text/javascript"); elm.InnerText = System.IO.File.ReadAllText(Environment.CurrentDirectory + @"\helperscripts.js"); ((HtmlElement)head[0]).AppendChild(elm); } 

therefore all helperscript.js methods can be called using

 webBrowser1.Document.InvokeScript("methodname"); 

here's a link for a script invoke: How to add Javascript to a WebBrowser control?

Hello

+11
Mar 22 '12 at 1:08
source share

Try adding file:// to the url.

+4
Oct 27 '10 at 2:43
source share

There is a long history of workarounds for this β€œsecurity fix” from MS. New behavior has been implemented since IE7. Take a look at the "base" tag and IE controls .

I have done the following:

  //TODO: if not mono var executableFilename = Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location); var keys = new[] { executableFilename, [vsname]+".vshost.exe" }; //check! Action<string, object, string> SetRegistryKeyOrFail = (key, val, regStr) => { var reg = Registry.CurrentUser.CreateSubKey(regStr); if (reg == null) throw new Exception("Failed registry: " + regStr); reg.SetValue(key, val); }; foreach (var key in keys) { SetRegistryKeyOrFail(key, 1, @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BLOCK_LMZ_IMG"); SetRegistryKeyOrFail(key, 0, @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BLOCK_LMZ_SCRIPT"); } 
+1
Aug 04 '11 at 16:10
source share

This is for security reasons. To do this, you need a web server, otherwise you can access any file in the system, which will be a big security hole.

In development mode, you can set, for example, on chrome:

 chrome.exe --allow-file-access-from-files 

And you can run your code.

0
Jun 03 2018-11-18T00:
source share



All Articles