[C#][JavaScript]WinForm與WebPage的JavaScript互通(二) - 動態加入並調用JavaScript
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(webBrowser1.Document.InvokeScript("GetVar", new object[] { "executeCount" }).ToString());
}
public void OnWebPageReady()
{
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
element.text = "function GetVar(varName) { return eval('(' + varName + ')'); }";
head.AppendChild(script);
}
}</pre></div>
public void OnWebPageReady()
{
webBrowser1.Document.InvokeScript("ShowAlert", new object[] { "WebPage Ready..." });
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
element.text = "function GetJsonValue(json, member) { return eval('(' + json + '.' + member+ ')'); }";
head.AppendChild(script);
MessageBox.Show(webBrowser1.Document.InvokeScript("GetJsonValue", new object[] { "{'version': '1.0'}", "version" }).ToString());
}
}</pre></div>
namespace WindowsFormsApplication3 { [PermissionSet(SecurityAction.Demand, Name = “FullTrust”)] [ComVisible(true)] public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
webBrowser1.DocumentText = @"<head><script>
var executeCount = 0;
function ShowAlert(alertMessage) {
++executeCount;
alert (alertMessage);
}
window.external.OnWebPageReady();</script></head>";
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("ShowAlert", new object[] { "alert message..." });
MessageBox.Show(webBrowser1.Document.InvokeScript("GetVar", new object[] { "executeCount" }).ToString());
}
public void OnWebPageReady()
{
webBrowser1.Document.InvokeScript("ShowAlert", new object[] { "WebPage Ready..." });
HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement script = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
element.text = "function GetVar(varName) { return eval('(' + varName + ')'); }";
head.AppendChild(script);
script = webBrowser1.Document.CreateElement("script");
element = (IHTMLScriptElement)script.DomElement;
element.text = "function GetJsonValue(json, member) { return eval('(' + json + '.' + member+ ')'); }";
head.AppendChild(script);
MessageBox.Show(webBrowser1.Document.InvokeScript("GetJsonValue", new object[] { "{'version': '1.0'}", "version" }).ToString());
}
}
}