WinForm:与WinForm通信的Javascript错误

本文关键字:WinForm Javascript 错误 通信 | 更新日期: 2023-09-27 17:52:43

我正在开发一个应用程序来实现网站和c# WebForm之间的双向通信。WebForm可以通过按钮与网页的脚本通信,但是脚本不能与WebForm通信。当点击按钮时,给出错误:

'window.external' is null or not an object.

c#代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FirstCSharpApp
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            WebBrowser.AllowWebBrowserDrop = false;
            WebBrowser.IsWebBrowserContextMenuEnabled = false;
            WebBrowser.WebBrowserShortcutsEnabled = false;
            WebBrowser.ObjectForScripting = this;
            string curDir = Directory.GetCurrentDirectory();
            WebBrowser.Navigate(new Uri(String.Format("file:///{0}/Timeline.html", curDir)));
        }
        private void GoButton_Click(object sender, EventArgs e)
        {
            // Works!
            WebBrowser.Document.InvokeScript("test",
                new String[] { "called from client code" });
        }
        private void homeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebBrowser.GoHome();
        }
        private void goBackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebBrowser.GoBack();
        }
        private void goForwardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WebBrowser.GoForward();
        }
        public void Test(String message)
        {
            // Does not work, or apparently even exist
            MessageBox.Show(message, "client code");
        }
    }
}
HTML:

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

WinForm:与WinForm通信的Javascript错误

下面两行解决了我的问题。没有伴随的或相关的错误,这是随机的运气,我看到依赖没有声明。

// new
using System.Security;
...
// already in code
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]