Please use this code and add a script message handler and set the navigation delegate
NSString *js = @"document.body.style.background = \"#FF0000\";"; NSString *myScriptSource = @"alert('Hello, World!')"; WKUserScript *s = [[WKUserScript alloc] initWithSource:myScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]; WKUserContentController *c = [[WKUserContentController alloc] init]; [c addUserScript:s];
implement the script message handler "WKScriptMessageHandler" with the method name
#pragma mark -WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name isEqualToString:@"buttonClicked"]) { self.buttonClicked ++; }
}
and post js message form like this
var button = document.getElementById("clickMeButton"); button.addEventListener("click", function() { var messgeToPost = {'ButtonId':'clickMeButton'}; window.webkit.messageHandlers.buttonClicked.postMessage(messgeToPost); },false);
you will get a callback
source share