// Create a WKWebView instance
self.webView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:self.webConfig];
// Delegate to handle navigation of web content
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
setup accessor for self.webConfig
#pragma mark - accessors
-(WKWebViewConfiguration*) webConfig {
if (!_webConfig) {
// Create WKWebViewConfiguration instance
_webConfig = [[WKWebViewConfiguration alloc]init];
// Setup WKUserContentController instance for injecting user script
WKUserContentController* userController = [[WKUserContentController alloc]init];
// Add a script message handler for receiving "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.buttonClicked.postMessage script message
[userController addScriptMessageHandler:self name:@"buttonClicked"];
// Get script that's to be injected into the document
NSString* js = [self buttonClickEventTriggeredScriptToAddToDocument];
// Specify when and where and what user script needs to be injected into the web document
WKUserScript* userScript = [[WKUserScript alloc]initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
// Add the user script to the WKUserContentController instance
[userController addUserScript:userScript];
// Configure the WKWebViewConfiguration instance with the WKUserContentController
_webConfig.userContentController = userController;
}
return _webConfig;
}
implement script message handler method from protocol
#pragma mark -WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"buttonClicked"]) {
self.buttonClicked ++;
}
// JS objects are automatically mapped to ObjC objects
id messageBody = message.body;
if ([messageBody isKindOfClass:[NSDictionary class]]) {
NSString* idOfTappedButton = messageBody[@"ButtonId"];
[self updateColorOfButtonWithId:idOfTappedButton];
}
}
and post the message form js like this
var button = document.getElementById("clickMeButton");
button.addEventListener("click", function() {
var messgeToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messgeToPost);
},false);
this will help you because i also faced this issue while setting context nad calling method form JSExport