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

C# 如何将新javascript附加到当前HTML WebBrowser控件,c#,windows-phone-8,windows-phone,webbrowser-control,C#,Windows Phone 8,Windows Phone,Webbrowser Control,我试图在运行时插入自己的javascript来显示HTML(index.HTML-存在于IsolatedStorage中)。获取javascript对c 35;webBrowser_ScriptNotify的调用。我将如何实现这一点,以下是我实现这一点的尝试 string script = " <script type=\"text/javascript\"> function scriptNotify() { window.external.notify(\"runtime\");

我试图在运行时插入自己的javascript来显示HTML(index.HTML-存在于IsolatedStorage中)。获取javascript对c 35;
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;
}
它失败了,出现了一些系统错误

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.
堆栈跟踪:

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)

提前谢谢。

试试这样的方法:

string script=“//您的JS方法”;
string elementInnerText=(string)WebBrowser1.InvokeScript(“eval”,script)

请注意,当页面上至少有一个
标记时,
eval
可以工作

下面的解决方案使用
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'" });
}
异步任务ExecScriptNotify()
{
//加载空白页
var tcsLoad=new TaskCompletionSource();
this.webBrowser.NavigationCompleted+=(s,eArgs)=>
tcsLoad.TrySetResult(缺少类型);
this.webBrowser.NavigateToString(“”);
等待tcsLoad.Task;
//首先通过“setTimeout”添加脚本,JavaScript被初始化
var tcsInit=new TaskCompletionSource();
this.webBrowser.ScriptNotify+=(s,eArgs)=>
{
如果(eArgs.Value==“已初始化”)
tcsInit.TrySetResult(Type.Missing);
};
这个.webBrowser.InvokeScript(“setTimeout”,
新字符串[]{“window.external.notify('initialized'),“0});
等待tcsInit.Task;
//然后使用“eval”
这个.webBrowser.InvokeScript(“eval”,
新字符串[]{“document.body.style.backgroundColor='yellow'”});
}

感谢您回复Narek,但我不想从c#调用当前javascript函数。我想将新的javascript函数附加到当前在WebBrowser控件中打开的HTML文件中。在Windows Phone 8
webBrowser1中。不支持文档。您可以为解决方案提出一些其他解决方案吗。对于windows phone,请使用以下内容:string script=“function(){return document.getElementById('ElementID')。innerText;}”;string elementInnerText=(string)WebBrowser1.InvokeScript(“eval”,script);感谢您的快速回复,但如果我想在当前HTML中添加带有javascript的新脚本标记,那么我将如何实现这一点?感谢您的建议,我已经尝试了您的代码,并且工作良好。但是最后一行
document.body.style.backgroundColor='yellow'
我将其替换为我的代码
var scriptString=“var script=document.createElement('script');“+”script.type=\'text/javascript\”;“+”script.src='/rtemaster.js'”+“this.document.getElementsByTagName('head')[0].appendChild(脚本);”;调用脚本(“eval”,脚本字符串)@gofor.net,很高兴知道它在Windows Phone下工作。我有点惊讶
script.src='/rtemaster.js
也能工作。还是没有?
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'" });
}