我有一個Windows窗體應用程序和一個單獨的HTML頁面。兩人應該相互溝通。我遵循this microsoft link的指示。在我設置ObjectForScripting爲WebBrowser.ObjectForScripting = this;
之前,HTML頁面顯示正確。但是,在設置ObjectForScripting
之後,HTML將不會顯示在WebBrowser組件中。它給出錯誤「window.external爲null或不是對象。」WinForms:設置ObjectForScripting時,不顯示HTML
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>
你真的應該包括你的代碼,以防萬一有複製粘貼錯誤。這是最常見的錯誤之一。 –