6

我想使用WKWebviewAPI 注入脚本。由于某种原因它不起作用,我无法弄清楚。我已经尝试在Safari开发人员控制台中进行调试,但我也无法JavaScript在其中找到代码。

实现代码如下:

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

2 回答 2

4

alert默认情况下未实现WKWebView,因此即使您的用户脚本运行它也不会明显执行任何操作。您需要实施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)
}

我不认为注入的 JavaScript 实际上出现在 DOM 中的任何地方,它是WKWebView.

于 2017-12-14T18:48:34.250 回答
2

请使用这样的代码并添加脚本消息处理程序并设置导航委托

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

使用方法名称实现脚本消息处理程序“WKScriptMessageHandler”

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

}

并像这样发布消息表单js

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

您将收到回电

于 2017-02-28T06:31:24.843 回答