gpt4 book ai didi

c# - 从嵌入式浏览器通过 javascript 调用应用程序的功能?

转载 作者:行者123 更新时间:2023-11-30 18:55:00 25 4
gpt4 key购买 nike

我在 C# 应用程序中有一个嵌入式浏览器,我在其中显示静态网页。我可以通过 javascript 在嵌入式浏览器内的网页中按下一个按钮来调用应用程序的功能吗?

最佳答案

查看 WebBrowser.ObjectForScripting property .为 ObjectForScripting 属性设置一个类,它的公共(public)属性和方法将通过 window.external 对 JavaScript 可用。

示例(来自 MSDN)

using System;
using System.Windows.Forms;
using System.Security.Permissions;

[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
private WebBrowser webBrowser1 = new WebBrowser();
private Button button1 = new Button();

[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}

public Form1()
{
button1.Text = "call script code from client code";
button1.Dock = DockStyle.Top;
button1.Click += new EventHandler(button1_Click);
webBrowser1.Dock = DockStyle.Fill;
Controls.Add(webBrowser1);
Controls.Add(button1);
Load += new EventHandler(Form1_Load);
}

private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;

webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}

public void Test(String message)
{
MessageBox.Show(message, "client code");
}

private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
}

}

关于c# - 从嵌入式浏览器通过 javascript 调用应用程序的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2408402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com