Reputation: 2911
I have index.html and script.js in my project resources. And in html file, I try to link script script.js with it:
<script src="script.js"></script>
Also I have Form which have a WebBrowser control and its url is index.html. And no problem here.
The problem is when I test the application and run WebBrowser, it give me a script error which it's mean there's no file name script.js, and cannot link with it.
What I should type here instead of ????
??
<script src="????/script.js"></script>
Upvotes: 6
Views: 2054
Reputation: 2397
Okay, since you requested it, the basic idea is to read your JS file into a string, then create a script tag element and then insert it on the body. Also remember to set the JS file to Copy to Output Directory
from the properties window if you are using visual studio.
You have a JS file that looks like this:
alert("Include me");
You have CS file that looks like this:
using System.Windows.Forms;
using System.IO;
namespace stackoverflow
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var path = Path.Combine(System.Environment.CurrentDirectory, "test.html");
var page = System.IO.File.ReadAllText(path);
webBrowser1.Navigate(path);
webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted;
}
private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var newScript = webBrowser1.Document.CreateElement("script");
webBrowser1.Document.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, newScript);
var path =Path.Combine(System.Environment.CurrentDirectory, "test.js");
var script =File.ReadAllText(path);
newScript.InnerText = script;
}
}
}
I used an HTML file that looks like this:
<!doctype html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Test</title>
</head>
<body>
<div id="container">
<h1>Test Text</h1>
</div><!-- content container -->
<script>
</script>
</body>
</html>
When I did this, I ended up with a result that looks like this:
Upvotes: 1
Reputation: 125217
You can use either of following options:
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);
}
Upvotes: 3