Execute javascript on WKWebView

Hi, im tryign to execute a javascript line inside of the loaded page on a wkwebview, the line is "document.body.style.backgroundColor = '#212121';". That line will chang the background color of the page.


this is what i tried, its on the ViewDidLoad


chatWebView.evaluateJavaScript("document.body.style.backgroundColor = '#212121';", completionHandler: nil)


they recomended me to add the UIWebViewDelegate but this is wkwebview, and use the webViewDidFinishLoad.


How should i do?

You can use `WKNavigationDelegate` instead of `UIWebViewDelegate`.


import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    
    var webView: WKWebView!
    
    override func viewDidLoad() {
        //... assuming the `webView` is setup here
        webView.navigationDelegate = self
        //...
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.style.backgroundColor = '#212121';", completionHandler: nil)
    }
    
}

they recomended me to add the UIWebViewDelegate but this is wkwebview, and use the webViewDidFinishLoad.

As OOPer pointed out,

WKWebView
has a navigation delegate that you can use for this thing. Another option is to add a
WKUserScript
. Such scripts can be set to run automatically after the document has loaded via the
injectionTime
property.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"


WWDC runs Mon, 4 Jun through to Fri, 8 Jun. During that time all of DTS will be at the conference, helping folks out face-to-face.
Execute javascript on WKWebView
 
 
Q