WKWebview evaluateJavascript is not working, throws an error

孤者浪人 提交于 2019-11-30 08:06:20

问题


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!


回答1:


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:

  • webView:didFinishNavigation: (from WKNavigationDelegate)

I hope this helps someone.




回答2:


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.



来源:https://stackoverflow.com/questions/27849465/wkwebview-evaluatejavascript-is-not-working-throws-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!