Dynamically adding css to WebViews in Swift

Photo of colouring pencils by Jess Watters on Unsplash

This week, I needed to figure out how to dynamically add css to a webView in iOS and it was much easier than I thought it would be.

All you need to do is make use of the webViewdidFinish function in the WKNavigationDelegate and evaluateJavaScript

This code will change the background colour of the webpage you are displaying to red.

To show how this works, I created a simple sample app with a series of buttons with colour choices on:

Clicking on any of the buttons takes you to a webView which displays www.google.co.uk but the background colour of the webpage changes depending on the button chosen. So if you click on green you’re taken to this page:

To do this, in the ViewController I added an IBAction which performs the segue when a button is tapped. The button text is then passed through to the WebViewController:

In the WebViewController there is a function getHexColour which determines the hex code colour based on the colour set in the segue.

Then in webViewDidFinish I created the css and JavaScript and applied that to the webView using the evaluateJavascript function:

Here’s a link to the sample project code: https://github.com/Ceri-anne/WebViewCss