WKWebview evaluateJavascript is not working, throws an error
Asked Answered
E

2

17

I am trying to call an existent function from a remote site in a WKWebview:

function addtext (text) {
 jQuery("#webviewtest").html(text);
}

With:

[self.WebView evaluateJavaScript:@"addtext(\"This is a text from app\");" completionHandler:^(id Result, NSError * error) {
    NSLog(@"Error -> %@", error);
}];

But this is throwing an error:

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo=0x170c788c0 {NSLocalizedDescription=A JavaScript exception occurred}

This is so simple! I am must missing something really stupid!

Egwin answered 8/1, 2015 at 21:4 Comment(4)
Is jQuery loaded on that page?Postpaid
Yes, its a fully functional website, I am just building a bridge to make a facebook login works. And the Function also works when I normally call on the browser.Egwin
Try without jQuery: document.getElementById('webviewtest').innerHTML = text;. Maybe html method fails.Particle
Hey @Pinal, you've made me realise that was a DOM Ready problem. Look at my answer below. Cheers.Egwin
E
33

Found a solution, it was simple as I was expecting, I was adding the javascript before the view complete load the content (before the Dom Ready). So I just had to move my code to the delegate method below:

I hope this helps someone.

Egwin answered 9/1, 2015 at 2:8 Comment(4)
This is a solution! Obviusly but save me a lot of time thank you.Disincline
Did you implement the delegate?Egwin
Same for Android webview :DTired
I am having this issue in didFinishNavigation...Even with delay of 3 sec it still throws this error.Richia
T
4

I found that the problem was caused by the webView:didFinishNavigation: being called before the page content was actually loaded. I think the website is using angularjs.

I introduced a manual delay which seemed to d the trick for me :

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("loaded)")
    //abtn_run(UIButton())
    self.perform(#selector(performAction), with: nil, afterDelay: 3.0)    
}

and did my call here:

func performAction() {
    //This function will perform this after delay of 3 seconds
}

Ideally the best solution would have a listener push an event for angularjs "page ready" but I am not sure this is possible in wkwebview.

Toting answered 30/12, 2016 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.