This is the HTML, which is stored in a string resource:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
(function(){
window.external.hello()
})()
</script>
</body>
</html>
This is the contents of Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace JSIE
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("about:blank");
webBrowser1.Document.Write(String.Empty);
webBrowser1.Document.Write(Properties.Resources.DDocument);
webBrowser1.ObjectForScripting = new JSCallbacks();
}
}
}
and this is JSCallbacks.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace JSIE
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class JSCallbacks
{
public void hello() {
MessageBox.Show("Hello, world!");
}
}
}
When I run this, it can't access the hello()
method in the JavaScript window.external
object, and gives me a script error message box. I have tried using this
as the ObjectForScripting
, but it doesn't work either.
Got it: You have to use the DocumentText property to load HTML before the page is executed.