WinForm:与WinForm通信时出现Javascript错误

时间:2015-06-01 16:24:35

标签: javascript c# winforms

我正在开发一个应用程序来实现网站和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>

1 个答案:

答案 0 :(得分:0)

以下两行解决了我的问题。没有伴随或相关的错误,我看到依赖没有被宣布随机运气。

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