可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 configuration
WKUserScript
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!