How do I make a WebKit WebView use a CSS style sheet?
cocoa, css, macos, webkit, webview
Solution
You might need to include an html `<base>` element to tell the webview where it shoul be looking for the css files.
Problem
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: