WebBrowser link JavaScript file from project resources

I have index.html and script.js in my project resources. And in the html file I am trying to link script.js to it :

<script src="script.js"></script>

I also have a Form that has a WebBrowser element, and its URL is index.html . And there is no problem.

The problem is when I test the application and run WebBrowser , it gives me a script error, which means the script.js file name is missing, and cannot communicate with it.

What should I enter here instead of ???? ??

<script src="????/script.js"></script>

Here's the error: Script error

+5
source share
2 answers

You can use one of the following options:

  • Include the contents of the js file in the same html file.
  • Copy both html and js files to the same directory at runtime, for example, to the 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); } 
+2
source

Well, since you requested it, the main idea is to read your JS file in a line, then create a script tag element and then paste it into the body. Also, do not forget to set the JS file in 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 a 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 got a result that looks like this: enter image description here

+1
source

Source: https://habr.com/ru/post/1275561/


All Articles