WKUserScript无法正常工作

时间:2014-10-05 13:17:17

标签: javascript wkwebview wkuserscript wkwebviewconfiguration

我想使用WKWebview API注入脚本。由于某种原因,它不起作用,我无法弄明白。我已尝试在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];
    });

2 个答案:

答案 0 :(得分: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);

您将收到回电

答案 1 :(得分:2)

oauth_默认情况下未在alert中实施,因此即使您的用户脚本运行,也无法做任何事情。您需要实施WKWebView

runJavaScriptAlertPanelWithMessage

我不认为注入的JavaScript实际上出现在DOM的任何地方,它是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) } 内部的属性。

相关问题