tags:

views:

279

answers:

2

Is it possible to manipulate CSS data before it is parsed in WebKit?

I've tried using the delegate method

- (NSURLRequest *)webView:(WebView *)sender
                 resource:(id)identifier
          willSendRequest:(NSURLRequest *)request
         redirectResponse:(NSURLResponse *)redirectResponse
           fromDataSource:(WebDataSource *)dataSource

which I can make work by writing down my manipulated CSS, then returning an alternative NSURLRequest that points to it. This works fine, apart from the DOM tree then contains the path to the manipulated URLRequest, not the original, which is bad news for my app.

Can I manipulate the data in memory before it's parsed?

A: 

As long as you can keep it under the 10MB limit, there is always stringByEvaluatingJavaScriptFromString and then do some loading of the CSS dynamically.

slf
I need to manipulate existing CSS, not add my own, it's a very peculiar problem!
MT
do what Rob Napier is saying - the "C" in "CSS" means that anything can be overridden, you shouldn't have to rewrite anything
slf
+2  A: 

Just load a user style sheet to override whatever CSS you want (that's the "cascading" part of CSS). This is a core feature of WebKit.

WebPreferences setUserStyleSheetEnabled:

For an example of this in practice, you can look at PandoraBoy's PlayerController which has hooks for it (though I wound up not needing to actually use them). Look in -awakeFromNib.

EDIT: If you really need to substitute your own CSS file for the original in a way that's totally transparent to WebKit, that's possible but it's a bit more work, more confusing, and generally shouldn't be needed. That said, PandoraBoy did run into this problem, and there's a solution. Look at ResourceURLProtocol.

Rob Napier
This sounds interesting, not quite sure where I'd use it though, through the delegate?
MT
NSURLProtocols are below the layer of WebKit. Before your make web accesses, you call [NSURLProtocol registerClass:[ResourceURLProtocol class]], and then ResourceURLProtocol will be inserted into the chain for every URL-based request (i.e. WebKit). You'll need to study the docs on NSURLProtocol. This is a powerful tool; I don't recommend it for casual issues like overriding CSS, which are more easily done with a user style sheet. But if you need to really control the low-level URL fetch process, then it's worth learning.
Rob Napier
ah gotcha! Will give this a go, thanks a lot!
MT