WKWebView Evaluate Javascript without reloading page

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

Currently I can only figure out how to evaluate javascript by adding it to the webview's configuration's userContentController and reloading the page like so:

WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; [self.webView.configuration.userContentController addUserScript:script]; [self.webView reload];

How can I execute javascript on my WKWebView similarly to the old WebView's stringByEvaluatingJavaScriptFromString: so that I don't have to reload the page?

I'm trying to get something with the same effect as

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%d;', false); ", width]];

回答1:

[webView evaluateJavaScript:javascriptString completionHandler:nil];

performs the same function as the one you have listed for UIWebView



回答2:

You can only set the WKWebViewConfiguration at init time via the initializer

[[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];

All calls to the property configurationWKUserScript to a WKWebViewConfiguration which is never used - and therefore not working.

The right way to do it:

NSString *scriptString = @"Some javascript"; WKUserScript *script = [[WKUserScript alloc] initWithSource:scriptString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [userContentController addUserScript:script]; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.userContentController = userContentController; _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];

evaluateJavaScript: anymore.

STKWebKitViewController on GitHub. Maybe this will save you time, too!



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