6

I'm looking for a way to load my UIWebView with a local CSS file that should affect on the UIWebView's loadRequest.

For the clearness: I have an UIWebView that I loadRequest it with a website url. I also have a local CSS file that should affect this loadRequest url.

I want to load this CSS file onto the UIWebView.

Thanks,

jkigel
  • 1,592
  • 6
  • 28
  • 49

3 Answers3

3

This stackoverflow question appears to have one or two answers that may help you.

You need to load the local CSS (using a method not unlike @Shrey uses, but looking for your CSS file), and somehow inject it into the page, and the only way appears to be to use:

[webview stringByEvaluatingJavaScriptFromString:someJavascriptToInjectCSS];

and some clever Javascript to modify the page to add the CSS in.

Hope this helps point you in the right direction. I have used this method to inject stuff into pages, so it does work, but I don't know Javascript well enough to write the code to inject your CSS into the page.

Community
  • 1
  • 1
iandotkelly
  • 9,024
  • 8
  • 48
  • 67
  • Sorry, I messed up the link on the answer - now edited. There is an answer on that page which appears to do what you want, in including the js. – iandotkelly Jul 29 '11 at 15:59
  • Thanks, but is it possible to apply custom css files on UIWebView that loads sites such as Google or should I give up for this option? – jkigel Jul 29 '11 at 16:09
  • Yes, you can use the answer in the SO question - the answer I am referring to is: http://stackoverflow.com/questions/1893715/is-it-possible-to-use-stringbyevaluatingjavascriptfromstring-with-javascript-whic/1895864#1895864 This answer shows loading of a CSS from a local file and injecting it into the web-view. – iandotkelly Jul 29 '11 at 16:13
0

This is the Swift version.

Load the css file on the webViewDidFinishLoad delegate method and use stringByEvaluatingJavaScriptFromString. Credits here

 func loadWebViewStyles() {
        guard let cssPath = NSBundle.mainBundle().pathForResource("theme", ofType: "css") else {
            return
        }

        let loadStyles = "var script = document.createElement('link');  script.type = 'text/css'; script.rel = 'stylesheet'; script.href = '\(cssPath)'; document.getElementsByTagName('body')[0].appendChild(script);"

        webView.stringByEvaluatingJavaScriptFromString(loadStyles)
    }
Community
  • 1
  • 1
Rodrigo Gonzalez
  • 723
  • 7
  • 15
-1

try this:

[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];

Shrey
  • 1,959
  • 2
  • 21
  • 44
  • 1
    don't think that's going to do what OP is asking for. For starters it is a local CSS file they want to load, not an html file, then they want to inject the CSS into a page that doesn't reference it. – iandotkelly Jul 29 '11 at 14:57
  • Then try using webview delegate methods. – Shrey Jul 29 '11 at 15:04