As an iOS developer, sometimes we should load a web page in our app with the help of WKWebView.

We are not allowed to use UIWebView since iOS 12 in our app.

Most of the times we may be requested to load a URL, but sometimes they ask us to inject javascript into the loaded page or maybe CSS, I know it’s weird to inject it directly within the app, There are too many ways 😕, but we are developer, we can say its wrong, but we have no choice, It should be implemented.

When we were using UIWebView, we injected javascript into a full web page with the help of this function.

So since we are not going to use UIWebView anymore, I just said it for more info. WKWebView is what we are going to use in the app, and we are going to work on it.

Error handling is essential, but it isn’t our primary purpose for now

With the help of this code, injection is possible, and I will explain each step:

load the URL I use this function to read the content of javascript and CSS file Now I am going to create WKUserScript which is responsible for injecting script into the webpage I add those scripts to the WKWebView instance configuration user controller

This code doesn’t work because we inject scripts directly into the webpage, I asked from a web developer, he explains how should I inject it into the web page, take a look a code below:

What has changed than before? I’ve added an encode to base 64 function and added our file contents into to javascript code before injection. Here is how it works.

It creates a javascript function Get the first head tag in Html Create a style or script Set style type text/javascript or text/css Set inner Html with our encoded file contents Append it to the parent

Now it works very well, and the trick was creating a new tag and append it to the parent. Since we are all looking for the fastest way to solve the problem, I will also provide objective-c code 😎.

The project repo is available here

It was a quick guide to inject javascript and CSS to the loaded webpage, and I covered both swift and objective-c code to make the copy and paste easier 🤪.

Thanks for reading this article if you enjoyed, please share it with others😊.

I am waiting to see your comment or recommendation in the comment section.

Feel free to contact me via LinkedIn