如何将本地脚本文件添加到WebBrowser控件的HTML? [英] How do I add a local script file to the HTML of a WebBrowser control?

查看:491
本文介绍了如何将本地脚本文件添加到WebBrowser控件的HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是非常愚蠢的。我已经尝试了一堆不同的方式,它只是不工作。我有一个WebBrowser控件WinForms应用程序。如果我有一个原始的HTML文件,试试我的桌面上使用相同字符串SRC,我放在一起SRC工作正常。但堵漏同样的东西到WebBrowser控件将无法正常工作。



下面是我的代码:

  HtmlElementCollection头= this.wbPreview.Document.GetElementsByTagName(头); 
如果(头!= NULL)
{
的HtmlElement榆树= this.webBrowserControl.Document.CreateElement(脚本);
串MYSOURCE = Environment.CurrentDirectory + @\MyScriptFile.js
elm.SetAttribute(src用户,MYSOURCE);
elm.SetAttribute(型,文/ JavaScript的);
((的HtmlElement)头部[0])的appendChild(榆)。
}



web浏览器并没有拿到剧本。但是,如果我改变MYSOURCE外部资源(通过http://)!,​​它工作正常。



帮助


< DIV CLASS =h2_lin>解决方案

我想出了您的文章,同时与东西玩弄我以下工作:

  HtmlElementCollection头= webBrowser1.Document.GetElementsByTagName(头); 
如果(头!= NULL)
{
的HtmlElement榆树= webBrowser1.Document.CreateElement(脚本);
elm.SetAttribute(型,文/ JavaScript的);
elm.InnerText = System.IO.File.ReadAllText(Environment.CurrentDirectory + @\helperscripts.js);
((的HtmlElement)头部[0])的appendChild(榆)。
}



,所以helperscript.js的所有方法都可以使用调用



  webBrowser1.Document.InvokeScript(methodName的); 



,这里作为脚本调用一个参考:的如何WebBrowser控件?



问候注入的JavaScript


This seems really dumb. I've tried a bunch of different ways and it's just not working. I have a WinForms app with a WebBrowser control. If I try with a raw html file on my desktop using the same src string, the src I put together works fine. But plugging the same stuff into the WebBrowser control won't work.

Here's my code:

HtmlElementCollection head = this.wbPreview.Document.GetElementsByTagName( "head" );
if (head != null)
{
    HtmlElement elm = this.webBrowserControl.Document.CreateElement("script");
    string mySource = Environment.CurrentDirectory + @"\MyScriptFile.js";
    elm.SetAttribute("src", mySource);
    elm.SetAttribute("type", "text/javascript");
    ((HtmlElement)head[0]).AppendChild(elm);
}

The WebBrowser doesn't get the script. However, if I change "mySource" to an external resource (via http://), it works fine!

Help!

解决方案

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控件的HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆