[webkit-help] How to load a file:// image from a webview loaded with a base URL?

Adam Roben aroben at apple.com
Fri Jun 25 08:32:53 PDT 2010

On Jun 24, 2010, at 3:37 PM, Dan Wood wrote:

> I'm seeing an odd behavior, and I wonder if it is a regression in Safari 5's webkit, and if there is a workaround.
> I have an HTML string which I have loaded up from a remote website, and modified slightly to include an image with a source of a local file:// URL.
> Then I try to load it into my webview with -[WebFrame loadHTMLString:baseURL:]. I pass in the base URL so that the images with relative paths will show properly.

What is the scheme of the base URL you're passing in?

> This works fine, except that my file:// image does not load!  It's not even requested, if I monitor the resource load delegate!

> The markup seems fine, and it has definitely been parsed when I examine my WebView with the inspector.  Just, no request for the image.

WebKit considers certain URL schemes to be "local". One of these is file:. Pages with non-local schemes aren't allowed to load resources from local schemes for security reasons. (E.g., it would be bad if http://www.example.com/ could use <iframe src=file:///etc/passwd> to read your passwords!)

My guess is that the base URL you're passing has a non-local scheme.

> If I try to load the HTML with a nil base URL, then my file://-URL-based image shows up just fine.

When you pass no base URL, WebKit makes up a unique URL that uses the applewebdata: scheme. WebKit treats this scheme as a local scheme, so you can load other local resources (such as file: resources). I believe this is done for compatibility reasons.

> This seems like either like a regression -- I can't believe that a base URL would affect being able to load up a local URL.  Or is this actually as expected?

As I've described above, this is expected.

> Any ideas on a workaround?  (I tried splicing in <base href=...> instead of the base URL; the problem is that the initial request becomes about:blank, so links to "#" sections don't work.  I guess I can put my local image up on the web...)

One workaround is to use a custom URL scheme for your base URL, and to tell WebKit to treat that scheme as a local scheme. You can do this with +[WebView registerURLSchemeAsLocal:].

A potentially better workaround is to use a custom URL scheme to load local resources, rather than using file: directly. An NSURLProtocol subclass can be used to implement this. I say this is "potentially better" because you can make your NSURLProtocol subclass restrict which files can be loaded (while with file: you'd be allowing any file on the whole system to be loaded).


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-help/attachments/20100625/fe92f70e/attachment.html>

More information about the webkit-help mailing list