2010-10-27 8 views
11

Esto parece realmente tonto. Lo intenté de varias maneras y simplemente no funciona. Tengo una aplicación WinForms con un control WebBrowser. Si intento con un archivo html sin formato en mi escritorio usando la misma cadena src, el src que armé funciona bien. Pero conectar las mismas cosas en el control WebBrowser no funcionará.¿Cómo agrego un archivo de script local al HTML de un control WebBrowser?

Aquí está mi código:

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); 
} 

El WebBrowser no recibe la secuencia de comandos. Sin embargo, si cambio "mySource" a un recurso externo (a través de http: //), ¡funciona bien!

¡Ayuda!

Respuesta

11

me ocurrió en su puesto, mientras que jugando con las cosas siguientes trabajó para mí:

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); 
} 

, por lo que todos los métodos de helperscript.js pueden ser invocado por medio de

webBrowser1.Document.InvokeScript("methodname"); 

, aquí como referencia para la invocación por la escritura: How to inject Javascript in WebBrowser control?

saludos

+1

recibiendo este error: {"La propiedad no es compatible con este tipo de HtmlElement."} – MonsterMMORPG

+0

probablemente solo funcione en IE – womd

+0

Funciona, pero al intentar establecer un script grande para 'elm.InnerText', el proceso simplemente deja de responder por un buen rato. – Gildor

4

Intente agregar file:// a la URL.

+0

De hecho, me hice y he intentado todas las demás nomenclaturas sabido que yo era capaz de encontrar. He usado absolutos, parientes, usando URI en su lugar, etc. No ir. – IAmAN00B

0

Esto es por razones de seguridad. Necesita un servidor web para hacer eso, de lo contrario, puede acceder a cualquier archivo en un sistema que sería un gran agujero de seguridad.

En el modo Desarrollos, se puede establecer por ejemplo en el cromo:

chrome.exe --allow-file-access-from-files 

Y usted será capaz de ejecutar su código.

1

There is a long story sobre soluciones provisionales de esa "solución de seguridad" de MS. Se implementó un nuevo comportamiento a partir de IE7. Eche un vistazo a la etiqueta "base" y IE Feature controls.

hice lo siguiente:

    //TODO: if not mono 
       var executableFilename = Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location); 
       var keys = new[] { executableFilename, [vsname]+".vshost.exe" }; //check! 

       Action<string, object, string> SetRegistryKeyOrFail = 
        (key, val, regStr) => 
         { 
          var reg = 
           Registry.CurrentUser.CreateSubKey(regStr); 
          if (reg == null) throw new Exception("Failed registry: " + regStr); 
          reg.SetValue(key, val); 
         }; 

       foreach (var key in keys) 
       { 
        SetRegistryKeyOrFail(key, 1, @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BLOCK_LMZ_IMG"); 
        SetRegistryKeyOrFail(key, 0, @"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BLOCK_LMZ_SCRIPT"); 
       } 
Cuestiones relacionadas