How do I add a local script file to the HTML of a WebBrowser control?
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
WebBrowser link JavaScript file from Project Resources
You can use either of following options:
- Include the js file content in the same html file.
- Copy both html and js file into the same directory at run-time, for example a temp directory.
Example
private void Form1_Load(object sender, EventArgs e)
{
var path = System.IO.Path.GetTempFileName();
System.IO.File.Delete(path);
System.IO.Directory.CreateDirectory(path);
var indexPath = System.IO.Path.Combine(path, "index.html");
var scriptPath = System.IO.Path.Combine(path, "script.js");
System.IO.File.WriteAllText(indexPath, Properties.Resources.index);
System.IO.File.WriteAllText(scriptPath, Properties.Resources.script);
webBrowser1.Navigate(indexPath);
}
Local load of HTML/Javascript file in C# WebBrowser object not loading correctly?
When i paste this into an html file and open on internet explorer, it display a message that it blocked activex/script content. Change Internet Options > Advanced > Security > Allow active content to run in files on My Computer. If the warning goes away in IE, then it should work in WebBrowser object
Load local HTML file in a C# WebBrowser
- Do a right click->properties on the file in Visual Studio.
- Set the Copy to Output Directory to Copy always.
Then you will be able to reference your files by using a path such as @".\my_html.html"
Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.
If you use a sub folder, that too will be copied in to the bin folder so your path would then be @".\my_subfolder\my_html.html"
In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.
This is what you need:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
You'll have to change the variables and names of course.
Open local file in System.Windows.Forms.WebBrowser control
I have found a work around which will keep me going for the time being but I would still be interested if anyone has an explanation for the behaviour described.
By faking a remote file path, I can cause the Navigating
event to fire as it did for actual remote files, then in the Navigating
event, I re-write the path to re-reference the local file as follows:
Setting Document Text
Change:
programHtml.AppendLine(String.Format("<a href='file://{0}'>{1}</a><br />", progInfo.FullName, progInfo.Name.ToUpper))
To:
programHtml.AppendLine(String.Format("<a href='{0}' target='_top'>{1}</a><br />", progInfo.FullName.ToLower.Replace("c:", "\\faked"), progInfo.Name.ToUpper))
'note the `\\faked`
Handling the Navigating
event
Add the following:
Dim filepath As String = e.Url.OriginalString.Replace("\\faked", "c:")
If File.Exists(filepath) Then
....
How to inject Javascript in WebBrowser control?
For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work:
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");
This answer explains how to get the IHTMLScriptElement
interface into your project.
Related Topics
Scope_Identity() Always Returning 0
Insert into SQL Db a String That Contain Special Character '
C# Invalid Attempt to Call Read When Reader Is Closed
How to Convert This C# Rijndael Encryption to PHP
Get List of Certificates from the Certificate Store in C#
ASP.NET MVC 4 + Ninject MVC 3 = No Parameterless Constructor Defined for This Object
Call C++ Function Pointer from C#
Onchange Event for HTML.Dropdownlist
C# Async/Await Progress Event on Task<> Object
Mvc-Web API: 405 Method Not Allowed
How to Pass Strings from C# to C++ (And from C++ to C#) Using Dllimport
.Net Decompiler for MAC or Linux
Is Tls 1.1 and Tls 1.2 Enabled by Default for .Net 4.5 and .Net 4.5.1
How to Add a Reference to an Unmanaged C++ Project Called by a C# Project
Code with Undefined Behavior in C#