Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView Evaluate Javascript without reloading page

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]];
like image 842
JuJoDi Avatar asked Jul 22 '14 00:07

JuJoDi


2 Answers

[webView evaluateJavaScript:javascriptString completionHandler:nil];

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

like image 102
rvijay007 Avatar answered Nov 09 '22 08:11

rvijay007


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!

like image 45
stk Avatar answered Nov 09 '22 08:11

stk