Reputation: 12276
I made an html wich links to a CSS file, open it in browsers, and the styles show correctly.
Then I load it in a WebView and the styles don't show.
I even tried to insert a <link>
into the DOM from Objective-C, which is my ultimate goal, but neither worked.
Do I have to enable CSS on the webView somehow?
edit:
the CSS include in the html:
<link rel='StyleSheet' href="file://localhost/Users/petruza/Source/Scrape/build/Debug/Scrape.app/Contents/Resources/Scrape.css" type="text/css" >
the CSS inserted in the DOM: (I checked and it does get inserted)
NSURL *cssUrl = [[NSBundle mainBundle] URLForResource:@"Scrape.css" withExtension: nil];
DOMDocument* dom = [[web mainFrame] DOMDocument];
[window setTitleWithRepresentedFilename: lastRunScript];
DOMElement* link = [dom createElement:@"link"];
[link setAttribute:@"rel" value:@"StyleSheet"];
[link setAttribute:@"type" value:@"text/css"];
[link setAttribute:@"href" value: [cssUrl absoluteString]];
DOMElement* head = (DOMElement*) [[dom getElementsByTagName:@"head"] item:0];
DOMElement* headFirstChild = head.firstElementChild;
if( headFirstChild )
[head insertBefore:link refChild:(DOMNode *)headFirstChild];
else
[head appendChild:(DOMNode *)link];
edit2:
Same exact html shown in my WebView and in Safari:
Upvotes: 6
Views: 3547
Reputation: 138051
Another alternative would be to use the user stylesheet preference of the WebView:
WebView* webView = /* snip */;
webView.preferences.userStyleSheetEnabled = YES;
webView.preferences.userStyleSheetLocation = [NSURL fileURLWithPath:@"my/stylesheet.css"];
Assuming that the style data can be reached with an URL, this is probably the simplest way to do it.
Upvotes: 3
Reputation: 12276
Sorry, my bad, I was loading the WebView with a string and not providing a baseURL:
Before:
[[web mainFrame]
loadHTMLString: output
baseURL:[NSURL URLWithString:@""]];
After:
[[web mainFrame]
loadHTMLString: output
baseURL:[NSURL URLWithString:@"file://localhost/"]];
It works now!
Upvotes: 1
Reputation: 64700
You might need to include an html <base>
element to tell the webview where it shoul be looking for the css files.
Upvotes: 3