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

≯℡__Kan透↙ 提交于 2019-11-27 22:19:49
womd

i came up on your post, while playing around with things following worked for me:

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

, so all methods of helperscript.js can be invoked using

webBrowser1.Document.InvokeScript("methodname");

, here as a reference for the script invoke: How to inject Javascript in WebBrowser control?

greetings

Try adding file:// to the URL.

There is a long story about workarounds of that "security fix" from MS. New behavior was implemented starting from IE7. Take a look into "base" tag and IE Feature controls.

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

This is because of security reasons. You need a webserver to do that, else you can access any file on a system which would be a big security hole.

In developement mode, you can set e.g on chrome:

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

And you will be able to run your code.

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