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,

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
Yes, you can use the answer in the SO question - the answer I am referring to is: stackoverflow.com/questions/1893715/… This answer shows loading of a CSS from a local file and injecting it into the web-view.
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)
    }

Comments

-1

try this:

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

2 Comments

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.
Then try using webview delegate methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.