如何将新的javascript附加到当前的HTML WebBrowser控件

时间:2014-08-21 08:52:12

标签: c# windows-phone-8 windows-phone webbrowser-control

我试图在运行时插入我自己的javascript来呈现HTML(index.html - 存在于IsolatedStorage中)。要从javascript拨打电话到c#webBrowser_ScriptNotify。我将如何实现这一目标,这是我尝试实现这一目标。

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

更新

这里我尝试在当前打开的HTML页面中注入脚本标记。

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

因系统错误而失败。

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)

提前致谢。

3 个答案:

答案 0 :(得分:1)

请注意,eval已知在页面上至少有一个<script>标记时才会生效。

以下解决方案使用webBrowser.InvokeScript("setTimeout", ...)执行一些JavaScript(从而启用eval)。我使用Windows应用商店应用测试了这种方法,它在那里工作。我希望它也适用于Windows Phone,希望你能够确认它。

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

答案 1 :(得分:0)

答案 2 :(得分:0)

尝试这样的事情:

string script =&#34; //你的JS方法&#34 ;; string elementInnerText =(string)WebBrowser1.InvokeScript(&#34; eval&#34;,script);