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:
CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.
Webkit code may need to be added in CSS to ensure it renders correctly on Chrome and Safari due to the lack of cross-compatibility. The importance of webkit is related to CSS3, which is a new generation of CSS modules that enables transition effects, multiple column layouts, and animation.
There are three types of CSS which are given below: Inline CSS. Internal or Embedded CSS. External CSS.
You might need to include an html <base>
element to tell the webview where it shoul be looking for the css files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With