How to append new javascript to current HTML WebBrowser Control

有些话、适合烂在心里 提交于 2020-01-06 03:46:06

问题


I am trying to insert my own javascript to present HTML(index.html - present in IsolatedStorage) at runtime. To get call from javascript to c# webBrowser_ScriptNotify. How I will achieve this, here is my attempts to achieve this.

string script = " <script type=\"text/javascript\"> function scriptNotify() { window.external.notify(\"runtime\");}</script>";
byte[] param = GetBytes(script);

webBrowser.Navigate(new Uri("/index.html", UriKind.Relative), param,"Content-Type: application/x-www-form-urlencoded");


private void webBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{            
   if (e.Value.ToString().Equals("runtime"))
   {
       Debug.WriteLine("Call from dynamic javascript");
   }
}   

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

Update

Here my new try to inject script tag in currently opened HTML page.

var scriptString = "var script=document.createElement('script');"
                                   + "script.type=\"text/javascript\";"
                                   + "script.InnerHTML=\"function callMe(){window.external.notify(\"runtime\")};\""
                                    + "document.getElementsByTagName('head')[0].appendChild(script);";

webBrowser.InvokeScript("eval", scriptString);

its failed with some system error.

System.SystemException was unhandled
Message: An unhandled exception of type 'System.SystemException' occurred in Microsoft.Phone.Interop.ni.dll
Additional information: An unknown error has occurred. Error: 80020101.

StackTrace:

at Microsoft.Phone.Controls.NativeMethods.ValidateHResult(Int32 hr)
   at Microsoft.Phone.Controls.WebBrowserInterop.InvokeScript(String scriptName, String[] args)
   at Microsoft.Phone.Controls.WebBrowser.InvokeScript(String scriptName, String[] args)
   at WebBrowserJSTest.MainPage.webBrowser_LoadCompleted(Object sender, NavigationEventArgs e)

Thanks in advance.


回答1:


Note that eval is known to work when there's already at least one <script> tag on the page.

The following solution uses webBrowser.InvokeScript("setTimeout", ...) to execute some JavaScript (and thus enable eval). I tested this approach with a Windows Store app and it works there. I expect it to work with Windows Phone too, hopefully you'd be able to confirm it.

async Task ExecScriptNotify()
{
    // load a blank page
    var tcsLoad = new TaskCompletionSource<object>();
    this.webBrowser.NavigationCompleted += (s, eArgs) =>
        tcsLoad.TrySetResult(Type.Missing);
    this.webBrowser.NavigateToString("<body></body>");
    await tcsLoad.Task;

    // first add a script via "setTimeout", JavaScript gets initialized
    var tcsInit = new TaskCompletionSource<object>();
    this.webBrowser.ScriptNotify += (s, eArgs) =>
    {
        if (eArgs.Value == "initialized")
            tcsInit.TrySetResult(Type.Missing);
    };
    this.webBrowser.InvokeScript("setTimeout", 
        new string[] { "window.external.notify('initialized')", "0" });
    await tcsInit.Task;

    // then use "eval"
    this.webBrowser.InvokeScript("eval", 
        new string[] { "document.body.style.backgroundColor = 'yellow'" });
}



回答2:


WebBrowser.InvokeScript Method




回答3:


try something like this:

string script = "//Your JS method "; string elementInnerText = (string)WebBrowser1.InvokeScript("eval", script);



来源:https://stackoverflow.com/questions/25422035/how-to-append-new-javascript-to-current-html-webbrowser-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!