6

I want to inject a script using WKWebview API. For some reason it isn't working and I can't figure it out. I've tried debugging in Safari developer console and I can't find the JavaScript code in there either.

Implementation Code as follows:

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];

    WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
    conf.userContentController = c;

    WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:conf];
    [self.view addSubview:webview];
    webview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
        [webview loadRequest:request];
    });
Avner Barr
  • 13,049
  • 14
  • 82
  • 152

2 Answers2

3

alert isn't implemented in WKWebView by default, so even if your user script runs it won't visibly do anything. You need to implement runJavaScriptAlertPanelWithMessage:

func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (() -> Void)) {
  let alert = UIAlertController.create(title: frame.request.url?.host, message: message, preferredStyle: .alert)
  alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
    completionHandler()
  }))
  present(alert, animated: true, completion: nil)
}

I don't think the injected JavaScript actually appears in the DOM anywhere, it's a property internal to the WKWebView.

BonzaiThePenguin
  • 1,293
  • 10
  • 17
2

Please use code like this and add script message handler and set 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];
// Add a script message handler for receiving  "buttonClicked" event notifications posted from the JS document using window.webkit.messageHandlers.buttonClicked.postMessage script message
    [c addScriptMessageHandler:self name:@"buttonClicked"];

WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
conf.userContentController = c;

WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:conf];
[self.view addSubview:webview];
webview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Do any additional setup after loading the view, typically from a nib.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
    [webview loadRequest:request];
});

implement script message handler "WKScriptMessageHandler" with method name

#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);

you will receive a call back

Anurag Soni
  • 1,039
  • 9
  • 14
  • @mrjimoy_05 what have you tried, it is implemented and tested, and this answer is about script message handler, you are executing js, i checked with your code on your question – Anurag Soni May 24 '17 at 10:32