Search code examples
c#webviewxamarinwebkitmonomac

Displaying a Webpage in a WebView Within a Window Programmatically Using MonoMac


I really didn't want to have to ask this here, because it seems to me this should be really basic and simple, but I can't find any good examples online after searching for several hours between yesterday and today. So, here goes:

I'm trying to experiment with an API that uses OAuth 2.0 authentication. In order to do that authentication, I'm trying to open a window with a webpage in it for the user to grant access to the application. For some reason, I thought this would be as simple as creating a new NSWindow and WebView, setting the content of the window to the WebView, and loading the page URL; however, when I run this, the window opens, but never displays anything. I tried using autolayout constraints, thinking maybe the webview just wasn't positioned properly, but that didn't work either. I took them out of the code below. I'm trying to do this in a xibless manner. Below is my code:

using AppKit;
using Foundation;
using CoreGraphics;
using WebKit;

namespace SampleApplication.Mac
{
    [Register ("AppDelegate")]
    public class AppDelegate : NSApplicationDelegate
    {
        public AppDelegate ()
        {
        }

        public override void DidFinishLaunching (NSNotification notification)
        {
            var window = new NSWindow (new CGRect (0, 0, 100, 100), NSWindowStyle.Borderless, NSBackingStore.Buffered, false);
            var webview = new WebView();
            webview.Frame = new CGRect (0, 0, 100, 100);
            window.ContentView = webview;
            webview.MainFrame.LoadRequest(new NSUrlRequest (new NSUrl ("https://google.com")));
        }

        public override void WillTerminate (NSNotification notification)
        {
            // Blah
        }
    }
}

I've done some Mac development before, but I've never used WebKit, so I might be missing some understanding somewhere. Any help would be greatly appreciated, as the documentation on this is not very good.


Solution

  • Well, it turns out the problem had nothing to do with the WebView at all. I feel really dumb about this, but the window that was showing up was the default one that is part of the Cocoa app template I used when I created the project. The window I was trying to make was not showing up at all! I kind of thought the dimensions seemed odd.

    In order to fix this, I simply needed to do the following after instantiating the window:

    window.MakeKeyAndOrderFront(null);
    

    Once I did this, the window displayed and the webpage loaded as I expected.