6

Voglio iniettare uno script utilizzando l'API WKWebview. Per qualche motivo non funziona e non riesco a capirlo. Ho provato il debug nella console per sviluppatori Safari e non riesco a trovare il codice JavaScript.WKUserScript non funziona

all'implementazione del codice come segue:

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]; 
    }); 
+2

Quindi, hai trovato una risposta alla tua domanda? – Bastian

+0

@Bastian puoi provare con il mio sollution se questo ti aiuterà –

risposta

2

Si prega di utilizzare il codice come questo e aggiungere gestore di messaggi di script e impostare delegato di navigazione

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

implementare script di gestione dei messaggi "WKScriptMessageHandler" con il nome del metodo

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

}

e inviare il modulo messaggio js come questo

var button = document.getElementById("clickMeButton"); 
button.addEventListener("click", function() { 
     var messgeToPost = {'ButtonId':'clickMeButton'}; 
     window.webkit.messageHandlers.buttonClicked.postMessage(messgeToPost); 
    },false); 

si riceverà una chiamata indietro

+0

Non funziona –

+0

@ mrjimoy_05 cosa hai provato, è implementato e testato, e questa risposta riguarda il gestore dei messaggi di script, stai eseguendo js, ​​ho controllato con il tuo codice sulla tua domanda –

0

alert non viene realizzato nella WKWebView di default, quindi, anche se lo script utente esegue non sarà visibile Fai qualcosa. È necessario implementare 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) 
} 

non credo che il JavaScript iniettato appare in realtà nel DOM da nessuna parte, si tratta di una proprietà interna al WKWebView.