Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept javascript file from loading in web view

I am using WKWebView to make a web view app

let url = NSURL(string: "http://www.example.com")
let request = NSURLRequest(url: url! as URL)
homeWebView.load(request as URLRequest)

But I want to intercept some javaScript file of this website before it loads to change functionality and make the app a bit native looking

Any help would be appreciated.

Thank You.

like image 302
Ankit Kumar Avatar asked Aug 26 '26 14:08

Ankit Kumar


1 Answers

Following is the complete example. I hope it will help you.

import UIKit

class ViewController: UIViewController,UIWebViewDelegate {

    private var webView: UIWebView!

    override func loadView() {
        webView = UIWebView(frame: .zero)
        webView.delegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // set the view controller title, navigation etc
        self.loadWebPage()
    }

    func loadWebPage() {
        let url = URL(string: "https://www.google.com.pk/")
        //    let localFileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "ExampleHtmlFileName", ofType: "html", inDirectory: "HtmlFilesFolderName")!)
        let myRequest = URLRequest(url: url!)
        webView.loadRequest(myRequest)
    }

    //MARK: UIWebView Delegate
    func webViewDidFinishLoad(_ webView: UIWebView) {

        let jsScript = "exampleJSMethod()"
        _ = webView.stringByEvaluatingJavaScript(from: jsScript)
    }


}
like image 102
Imran Khan Avatar answered Aug 29 '26 16:08

Imran Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!