Adding a click event listener on WKWebView not working

For some reason, Everything started working after adding the code after evaluating that javascript. I am still unable to know why.

Here is the code for the full extension so far:

extension WKWebView {
    /// Type of HTML element to get from DOM
    enum ElementType {
        /// ID Element
        case id
        /// Class element
        case `class`
    }
    
    /// List of errors for WKWebView injection
    enum InjectionError: Error {
        /// The Listener is already added
        case listenerAlreadyAdded
    }
    
    /// Cahnges the CSS Visibiltiy
    /// - Parameters:
    ///   - elementID: The name of the element
    ///   - isVisible: Wether or not is visible
    ///   - elementType: The type of element to get
    ///   - completion: Callback triggered went script has been appended to WKWebView
    func changeCSSVisibility(elementID: String, isVisible: Bool, elementType: ElementType, completion: ((Error?)->Void)?) {
        let script: String
        
        switch elementType {
        case .id:
            script = "document.getElementById('\(elementID)').style.visibility = \(isVisible ? "'visible'":"'hidden'");"
        case .class:
        script =
            """
            [].forEach.call(document.querySelectorAll('.\(elementID)'), function (el) {
              el.style.visibility = \(isVisible ? "'visible'":"'hidden'");
            });
            """
        }
        
        evaluateJavaScript(script, completionHandler: { (result, error) in
            completion?(error)
        })
    }
    
    /// Adds a event listener that will be call on WKScriptMessageHandler - didReceiveMessage
    /// - Parameters:
    ///   - elementID: The name of the element
    ///   - callbackID: The ID for the callback
    ///   - elementType: The type of element to get
    ///   - completion: Callback triggered went script has been appended to WKWebView
    func addEventListener(elementID: String, callbackID: String, elementType: ElementType, handler: WKScriptMessageHandler, completion: ((Error?)->Void)?) {
        let element: String
        
        switch elementType {
        case .id:
            element = "document.getElementById('\(elementID)')"
        case .class:
            element = "document.getElementsByClassName('\(elementID)')[0]"
        }
        
        let scriptString = """
            function callback () {
                console.log('\(callbackID) clicked!')
                window.webkit.messageHandlers.\(callbackID).postMessage({
                    message: 'WKWebView-onClickListener-\(callbackID)'
                });
            }

            \(element).addEventListener('click', callback);
            """
        
        if configuration.userContentController.userScripts.first(where: { $0.source == scriptString }) == nil {
            evaluateJavaScript(scriptString) { [weak self] (result, error) -> Void in
                guard let self = self else { return }
                
                if let error = error {
                    completion?(error)
                } else {
                    self.configuration.userContentController.removeScriptMessageHandler(forName: callbackID)
                    self.configuration.userContentController.add(handler, name: callbackID)
                    self.configuration.userContentController.addUserScript(WKUserScript(source: scriptString, injectionTime: .atDocumentEnd, forMainFrameOnly: false))
                }
            }
        } else {
            completion?(InjectionError.listenerAlreadyAdded)
        }
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top