Javascript WKWebviewevaluateJavascript 不工作,抛出错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27849465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:46:02  来源:igfitidea点击:

WKWebview evaluateJavascript is not working, throws an error

javascriptiosobjective-cwkwebviewwkwebviewconfiguration

提问by Rogers Sampaio

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

我正在尝试从 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!

这太简单了!我一定错过了一些非常愚蠢的东西!

回答by Rogers Sampaio

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:

找到了一个解决方案,它很简单,正如我所期望的,我在视图完成加载内容之前(在 Dom Ready 之前)添加了 javascript。所以我只需要将我的代码移动到下面的委托方法:

I hope this helps someone.

我希望这可以帮助别人。

回答by UKDataGeek

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.

我发现问题是由于webView:didFinishNavigation:在实际加载页面内容之前被调用造成的。我认为该网站正在使用 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.

理想情况下,最好的解决方案是让侦听器为 angularjs“页面就绪”推送一个事件,但我不确定这在 wkwebview 中是否可行。