Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a WebKit WebView use a CSS style sheet?

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:
enter image description here

like image 848
Petruza Avatar asked Jun 24 '11 18:06

Petruza


People also ask

How do you apply CSS styles to a web page?

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.

Do we need Webkit CSS?

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.

What are the 3 main types of CSS style sheets that can be used when creating a webpage?

There are three types of CSS which are given below: Inline CSS. Internal or Embedded CSS. External CSS.


2 Answers

You might need to include an html <base> element to tell the webview where it shoul be looking for the css files.

like image 80
Femi Avatar answered Sep 22 '22 14:09

Femi


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.

like image 43
zneak Avatar answered Sep 20 '22 14:09

zneak