WebBrowser链接项目资源中的JavaScript文件

Sha*_*hra 5 html javascript c# webbrowser-control winforms

我的项目资源中有index.htmlscript.js.在html文件中,我尝试将脚本script.js与它链接:

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

我还有一个具有WebBrowser控件的Form,其url是index.html.这里没问题.

问题是当我测试应用程序并运行WebBrowser时,它给我一个脚本错误,这意味着没有文件名script.js,并且无法与它链接.

我应该在这里输入什么而不是??????

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

这是错误: 脚本错误

Rez*_*aei 3

您可以使用以下任一选项:

  • 将js文件内容包含在同一个html文件中。
  • 在运行时将 html 和 js 文件复制到同一目录中,例如临时目录。

例子

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);
}
Run Code Online (Sandbox Code Playgroud)