0
public func isLoggedIn() -> Bool{
        var returnValue:Bool = true
        let wb: WKWebView = {
            let webView = WKWebView()
            return webView
        }()
        wb.load(URLRequest(url:URL(string:"https://www.google.com/" )!))
        wb.evaluateJavaScript("document.body.backgroundColor") { (result, error) in
            if let result = result {
                print ("result")
                print(result)
                if (result as! String == ""){
                   returnValue = false
                }
            }
        }
        return returnValue
    }

I want to evaluateJavaScript from WKWebview with that function but I always get the error

Optional(Error Domain=WKErrorDomain Code=3 "The WKWebView was invalidated" UserInfo={NSLocalizedDescription=The WKWebView was invalidated})
error getting color
Optional(Error Domain=WKErrorDomain Code=3 "The WKWebView was invalidated" UserInfo={NSLocalizedDescription=The WKWebView was invalidated})

this function is in a class userManager and is called in another UIViewController class with if (userManager().isLoggedIn()) I don't know why it won't work and sorry if that's just a dumb question. Thank you already for helping.

edit: Thanks to the people in the comments and for everyone that try something similar like I do then just use http request How do I make an HTTP request in Swift?

  • Do you keep a strong reference to your webview? If you don't, it will be deallocated. Also, you have to wait for content to load before running javascript. – Sulthan Jul 29 '21 at 21:15
  • @Sulthan Wdym by "keep a strong reference to your WebView?" And it's not actually displaying cuz I just need it to get text from an element from a website and I thought that would be the best way to do it. – skillgamer Jul 29 '21 at 21:22
  • What's this? let webView = WKWebView() – El Tomato Jul 30 '21 at 00:08
  • Where are you writing your code? – El Tomato Jul 30 '21 at 00:08
  • @ElTomato I have it in a separate class call usermanager and just call a function from it in another viewController (like that `userManager().isLoggedIn()`). So I use it to get data from a website(here the document.body.backgroundColor). – skillgamer Jul 30 '21 at 10:51
  • Added new information! (sorry I didn't really provided enough information) – skillgamer Jul 30 '21 at 11:07
  • Loading content and evaluating javascript are both asynchronous operations. What really happens is 1. you create a webview 2. you request loading 3. you request javascript evaluation 4. you return `false` from the method. 5. method has finished, therefore webview variable went out of scope and it will get deallocated 5. loading fails with error because webview is invalidated 6. javascript fails with error because webview got invalidation and content is not loaded yet anyway. In short, you cannot simply call asynchronous code from synchronous methods. – Sulthan Jul 30 '21 at 15:32

0 Answers0