Search code examples
macoscocoawebviewfontswebkit

Cocoa WebView (MacApp) - how to use custom fonts?


I have a WebView in a Cocoa application (macgap).

(NOTE I'm not talking about a UIWebView in an iOS app)

In my CSS file, there are some custom font declarations:

@font-face{
    font-family:'Quivira';
    src:url("./Quivira.ttf") format("truetype");
    font-weight:normal;
    font-style:normal;
}

I can't get these to load however - some sort of security issue I believe.

Sometimes, I can see there is an error in the console "Not allowed to load local resource: Quivira.ttf" (it doesn't always show this though)

What could be causing this? The index.html file is loaded via the file:/// protocol so there shouldn't be a security issue, as it is already local and should therefor be able to load local resources.

I'm thinking it could be a bug in webkit.

Is anyone able to load custom fonts in a Cocoa WebView?


Solution

  • I have tried two approaches to load webpages with custom fonts.

    • From the app bundle (using NSBundle)
    • From a local path specified by the user (using absolute path)

    In both cases I am successfully able to display Custom Fonts. There is a HTML file and beside it, a .ttf font file. In the HTML file I have defined @font-face in inline CSS.

    In the second case you can give any full path from local filesystem and the webview will load from that (like /Users/johndoe/Desktop/maiwebsite/index.html).

    Code is on Github.

    And from another answer on SO:

    1. Instead of getting the resource path and stapling a subpath onto it yourself, ask the bundle to give you the correct path.
    2. Instead of handling a path at all, ask the bundle to give you the correct URL. (Requires Mac OS X 10.6 or later.)

    If this doesn't help then could you put up your code somewhere so we can try to debug it?