Xcode – inserting CSS and Javascript into a UIWebView

Whilst creating an iPhone application recently we had a need to be able to insert out own custom stylesheet and javascript, or jquery into certain web pages loaded within a UIWebView within the application.

We did it in the webViewDidFinishLoad section of the ViewController.m file:

[CSSWebView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';"
"document.getElementsByTagName('head')[0].appendChild(script);”];

and

[CSSWebView stringByEvaluatingJavaScriptFromString:@"var link = document.createElement('link');"
"link.type = 'text/css';"
"link.rel = 'stylesheet';"
"link.href = 'http://[your url goes in here]/style.css’;”
“document.getElementsByTagName(‘head’)[0].appendChild(link);”];


About Karl Binder

Managing Director
Karl founded Adhere in 2006 with Bobbie Bhogal after running his previous Design company - 529 - for 3 years. Karl is also a founding Director of Birmingham’s creative sector representative body ‘Creative Republic’ and has worked with a large range of people within the region to form networks and a lobbying voice for the sector, opening avenues of communication with regional agencies and Birmingham council. In 2008 Karl was listed in Business Insider magazines top 42 under 42s in the region.
Find Karl on Google Plus

 
 


8 − = five