I have a Windows forms application and a separate HTML page. The two are supposed to communicate with each other. I followed the instructions from this microsoft link. Before I set the ObjectForScripting with WebBrowser.ObjectForScripting = this;, the HTML page displayed correctly. However, after setting ObjectForScripting, the HTML will not display in the WebBrowser component whatsoever. It gives the error "window.external is null or not an object."
C# code:
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:
function test(message) {
alert(message);
}
Call client code.
Talk1:
You really should include YOUR code, just in case there was a copy paste mistake. It is one of the most common errors.
Solutions1
It looks like you are missing these attributes on your form class.
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
You can set this property to any COM-visible object for which you want
its public properties and methods available to scripting code. You can
make a class COM-visible by marking it with the ComVisibleAttribute.
Talk1:
From my understanding on the docs, if it is public it will already be tagged as Com Visible. I tagged it anyway, and it did not fix my problem.