How to force WebKit WebView to use CSS stylesheet?

I made an html that references a CSS file, open it in browsers, and the styles are displayed correctly.
Then I load it into the WebView and the styles are not displayed.
I even tried to insert <link> into the DOM from Objective-C, which is my final goal, but it didn’t work.
Should I include CSS in webView somehow?

Editing:
CSS include in html:
<link rel='StyleSheet' href="file://localhost/Users/petruza/Source/Scrapp/build/Debug/Scrapp.app/Contents/Resources/Scrapp.css" type="text/css" >

CSS inserted in the DOM: (I checked and pasted)

 NSURL *cssUrl = [[NSBundle mainBundle] URLForResource:@"Scrapp.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:
The same html shown in my WebView and in Safari:
enter image description here

+6
source share
3 answers

You may need to include the html <base> element to tell the browser where it should look for css files.

+3
source

Another alternative would be to use a WebView custom table style preference:

 WebView* webView = /* snip */; webView.preferences.userStyleSheetEnabled = YES; webView.preferences.userStyleSheetLocation = [NSURL fileURLWithPath:@"my/stylesheet.css"]; 

Assuming style data can be reached using a URL, this is probably the easiest way to do this.

+3
source

Sorry, my bad one, I loaded the WebView with a string and did not provide baseURL:
Before:

 [[web mainFrame] loadHTMLString: output baseURL:[NSURL URLWithString:@""]]; 

After:

 [[web mainFrame] loadHTMLString: output baseURL:[NSURL URLWithString:@"file://localhost/"]]; 

Now it works!

+1
source

Source: https://habr.com/ru/post/891309/


All Articles