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]];
[webView evaluateJavaScript:javascriptString completionHandler:nil];
performs the same function as the one you have listed for UIWebView
You can only set the WKWebViewConfiguration
at init time via the initializer
[[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
All calls to the property configuration
are copied in a later stage of runtime (see docs and Header file). So basically what you´re doing with your first three lines of code is to set the 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];
After doing this, you won´t need evaluateJavaScript:
anymore.
P.S.: I´m using this code in my little project STKWebKitViewController
on GitHub. Maybe this will save you time, too!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With