我可以请你帮帮忙吗?
我在表单上有一组Web浏览器控件。所有Web浏览器都设置为webBrowser.ObjectForScripting = this;所以所有脚本调用都在表单的代码中进行管理。
我在代码中说:
public void Method1(string title)
{
WebBrowser wb = (WebBrowser)some-object;
MessageBox.Show(title + wb.Url.ToString());
}
如果通过JavaScript从一个Web浏览器控件调用此方法,如何获取调用此方法的Web浏览器实例(some-object):
<script>
window.external.Method1('Hello');
</script>
谢谢 !!
我看到一些常见的选择:
示例1 - 呼叫者自我介绍
[ComVisible(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var txt =
@"<html>" +
@"<body>" +
@"<a href=""#"" " +
@"onclick=""window.external.Method1(this, 'Hello');"">" +
@"Click here.</a>" +
@"</body>" +
@"</html>";
webBrowser1.ObjectForScripting = this;
webBrowser2.ObjectForScripting = this;
webBrowser1.DocumentText = txt;
webBrowser2.DocumentText = txt;
webBrowser1.Document.Window.Name = webBrowser1.Name;
webBrowser2.Document.Window.Name = webBrowser2.Name;
}
public void Method1(object sender, string s)
{
//sender is the anchor element
dynamic window = ((dynamic)((dynamic)sender).document).defaultView;
var windowName = window.Name;
var control = this.Controls.Find(windowName, true);
MessageBox.Show(s);
}
}
示例2 - Callee知道呼叫者
private void Form1_Load(object sender, EventArgs e)
{
var txt =
@"<html>" +
@"<body>" +
@"<a href=""#"" " +
@"onclick=""window.external.Method1('Hello');"">" +
@"Click here.</a>" +
@"</body>" +
@"</html>";
webBrowser1.ObjectForScripting = new ScriptingObject(webBrowser1);
webBrowser2.ObjectForScripting = new ScriptingObject(webBrowser2);
webBrowser1.DocumentText = txt;
webBrowser2.DocumentText = txt;
}
[ComVisible(true)]
public class ScriptingObject
{
WebBrowser webBrowser;
public ScriptingObject(WebBrowser w)
{
webBrowser = w;
}
public void Method1( string s)
{
//This class knows which `WebBrowser` control calls its methods.
MessageBox.Show(s);
}
}