kbd
kbd

Reputation: 4469

Closing a webpage running in a WPF WebBrowser

First a bit of background

I'm working on a Web application, that will be running within a WebBrowser, within a WPF application.

This is a temporary necessity while we're gradually moving functionality to the web app. As long as that's not finished, the WPF client is still needed. Ultimately the WPF client will phase out completely.

Now to the issue at hand

When the user closes the client (webpage), the webbrowser should catch that event and also close the window it is a child to.

I found this link describing what I would need: WebBrowser and javascript window.close()

Alas, I don't think the answer described there would still work, as it's not possible to even do a window.close(), because I'm not the one opening the window I'm running on. Browsers have (rightfully) tightened their security since then.

The question

Is there a way to trigger a Window close from the client, that bubbles up to the WPF?

Thanks.

Upvotes: 3

Views: 1800

Answers (2)

kbd
kbd

Reputation: 4469

That worked, thanks!

I did the following:

[ComVisible(true)]
public class ScriptManager
{
    protected Window Window { get; set; }

    public ScriptManager(Window window)
    {
        this.Window = window;
    }

    public void CloseWindow()
    {
        this.Window.Close();
    }
}

And in my Window (Loaded Event):

// Build browser
this.Browser = new WebBrowser();
this.Browser.Navigate(this.GetUri());
this.Browser.ObjectForScripting = new ScriptManager(this);

The client Javascript then does:

$scope.Close = function() {
    window.external.CloseWindow();
}

Upvotes: 1

Glen Thomas
Glen Thomas

Reputation: 10764

I have used a WebBrowser control to call methods in a WPF application from the JavaScript before using WebBrowser.InvokeScript and WebBrowser.ObjectForScripting

See this MSDN article How to: Implement Two-Way Communication Between DHTML Code and Client Application Code Also see this CodeProject article which looks like it might solve your problem Call a C# Method From JavaScript Hosted in a WebBrowser

[ComVisible(true)]
    public class ScriptManager
    {
        // Variable to store the form of type Form1.
        private Window _window;

        // Constructor.
        public ScriptManager(Window window)
        {
            // Save the form so it can be referenced later.
            _window = window;
        }

        // This method can be called from JavaScript.
        public void MethodToCallFromScript()
        {
            // Call a method on the form.
            _window.Close();
        }
    }

from code behind of Window:

webBrowser1.ObjectForScripting = new ScriptManager(this);

Upvotes: 1

Related Questions