5

I am trying to call javascript using OpenWebKitSharp from WinForms with .NET 4

Here is the code I am trying to use.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WebKit;
using WebKit.Interop;
using WebKit.JSCore;
using webkitForm.Properties;

namespace webkitForm
{
    public partial class Form1 : Form
    {

        WebKitBrowser webKitSharpBrowser = new WebKitBrowser();

        public Form1()
        {
            InitializeComponent();

            this.Controls.Add(webKitSharpBrowser);
            webKitSharpBrowser.Width = 600;
            webKitSharpBrowser.Height = 400;


        }


        private void button1_Click(object sender, EventArgs e)
        {
            webKitSharpBrowser.Preferences.AllowPlugins = true;
            webKitSharpBrowser.UseJavaScript = true;
            webKitSharpBrowser.Navigate("http://sandbox.icontact.com");


            webKitSharpBrowser.GetScriptManager.EvaluateScript("alert('An alert from C#!');"); //Call javascript?

        }

    }
}

I can't get javascript to fire for anything... there must be something that I am missing.

Thanks in advance.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
David Eaton
  • 564
  • 2
  • 10
  • 22
  • Well It appears that the answer is the question. Hum the reason why the alert did not toggle is a mystery to me, but other javascript works just fine.. I wondered why someone was giving me credit for this question.. because it works I guess... – David Eaton Sep 23 '12 at 00:51

2 Answers2

3

Well, it seems like it can't be done the way you want to:

if you are using .NET 4, calling a function is possible by using:

<webkitbrowser>.GetScriptManager.CallFunction("name", new Object[] { arg1, arg2, ...}); 

If you want to use .NET 2 you can use:

<webkitbrowser>.StringByEvaluatingJavaScriptFromString("name(arguments)")

- Open Webkit Sharp Issues

safejrz
  • 544
  • 1
  • 14
  • 26
mario.tco
  • 674
  • 1
  • 7
  • 19
0

I tested your code, it IS working, but calling the alert function only triggers an event (WebKitBrowser.ShowJavaScriptAlertPanel), you are responsible for handling that event and showing a message or updating a label, or anything else.

For example:

Browser.ShowJavaScriptAlertPanel += Browser_ShowJavaScriptAlertPanel;

and then handle the event:

private void Browser_ShowJavaScriptAlertPanel(object sender, WebKit.ShowJavaScriptAlertPanelEventArgs e)
{
    MessageBox.Show(e.Message);
}