Can I force all links in a WebView (or WebFrame) to be treated as absolute paths?
-
16-09-2019 - |
Question
So I'm working with WebKit's - WebView and WebFrame. I use a custom NSURLProtocol to retrieve the HTML for each request from a database. The problem arises from the fact that the links in the HTML are all relative, when they really ought to be absolute. For example, the page
foo/bar.html
May have a link in it that points to
foo/baz.html
The problem is that since the link is relative, the request ends up being for
/foo/foo/baz.html
So far, I've tried to work around this by comparing the two URLs and stripping off the common prefix - in this case 'foo/' - leaving me with foo/baz.html. This doesn't work for all possibilities, however, especially when there are multiple directories in the path. I do this in the "didStartProvisionalLoadForFrame:" method of my WebView's frameLoadDelegate.
Unfortunately, I do not have control over the HTML that I'm displaying, so modifying the links themselves is not an option.
Solution
Try being the main frame's resource load delegate, and implementing webView:resource:willSendRequest:redirectResponse:fromDataSource:
to modify the URL being requested. Send relativeString
to the request's URL to get the original relative URL, then use -[NSURL initWithString:baseURL:]
to create a new URL with the same relative string against the correct base URL.