WkWebKit - 加载页面上的javascript发现window.webkit未定义

时间:2015-09-24 21:27:57

标签: javascript ios webkit xcode7 wkwebview

我正在尝试使用WkWebKit在应用和页面之间来回交谈。我可以使用WkWebView evaluateJavascript方法让javaScript执行得很好,但是当我尝试在JavaScript页面上执行window.webkit.messageHandlers.myHandler.postMessage('hello world!')时,我发现window.webkit没有定义。 / p>

奇怪......我正在ios 8.4的iPad模拟器中运行。我认为这可以在原始版本8中找到,不是吗?

我找不到其他任何关于此的帖子,所以也许我做错了什么?

我甚至将我的Safari Developer连接到模拟器的浏览器,在控制台中我试着看看window.webkit是什么,当然,它不存在。

请注意,我添加了一个在页面加载时运行的初始脚本(我在javascript编辑器中看到了这一点 - 记录了消息)。我还添加了一个脚本消息处理程序...

[编辑:在此处添加更多代码详情] 这是我的代码:

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.
  NSLog(@"main view Controller viewDidLoad called...");

// if we are running on an OLD ios (pre v8) WKWebView will not exist.  So don't create it if it doesn't exist...
if (NSClassFromString(@"WKWebView")) {
    // WKWebView cannot be dragged onto storyboard, so have to create it manually here.
    // We have a "ContainerView" called _webContainer that this browser view will live inside
    // First we create a web view configuration object...
    WKWebViewConfiguration *wbConfig = [WKWebViewConfiguration alloc];
    wbConfig.mediaPlaybackAllowsAirPlay = true;
    wbConfig.mediaPlaybackRequiresUserAction = false; 
    // inject some Javascript into our page before it even loads...
    NSString *scriptSource = @"console.log('Hi from the iOS app hosting this page...'); window.hostedByWkWebView=true;";
    WKUserScript *userScript = [[WKUserScript alloc]
                                initWithSource:scriptSource
                                injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                forMainFrameOnly:YES];

    [wbConfig.userContentController addUserScript:userScript];
    [wbConfig.userContentController addScriptMessageHandler:self name:@"myHandler"]; // javascript to use this would be: window.webkit.messageHandlers.myHandler.postMessage


    // Ok, the config is created, now create the WkWebView instance, passing in this config...
    _webView = [[WKWebView alloc] initWithFrame: [_webContainer bounds] configuration:wbConfig];
    _webView.autoresizesSubviews = true;
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _webView.navigationDelegate = self;

    // Add the web view to the container view, and tell the container to automatically resize its subviews, height and width.
    [_webContainer addSubview:_webView];
    _webContainer.autoresizesSubviews = true;
    _webContainer.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

    // Set the URL for the webview and navigate there...
    NSString *fullURL = @"https://myurlgoeshere.com";

    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [_webView loadRequest:requestObj];
}
else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot create Web View" message:@"The web view used requires iOS 8 or higher.  Sorry." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"", nil];
    [alert show];
}

//...

5 个答案:

答案 0 :(得分:20)

我解决了问题,问题是,如果您将userContentController设置为新对象,则userContentController WKScriptMessageHandler将无法在Apple'中正确注册内部代码:

WKUserContentController *userContentController = [WKUserContentController new];
userContentController.addScriptMessageHandler(self, name: "jockey")
userContentController.addScriptMessageHandler(self, name: "observe")
webView.configuration.userContentController = userContentController

使用Apple已经实例化的userContentController修复:

webView.configuration.userContentController.addScriptMessageHandler(self, name: "jockey")
webView.configuration.userContentController.addScriptMessageHandler(self, name: "observe")

答案 1 :(得分:4)

window.webkit命名空间仅出现在带有脚本消息处理程序的webview中。 确保已调用WKUserContentController的addScriptMessageHandler方法。

答案 2 :(得分:3)

我遇到了这个SO,因为我遇到了同样的问题,这就是我使用自定义CustomContentControllerWKUserContentController)实例的子类解决它的方法。

let userContentController = CustomContentController()
let webViewConfiguration = WKWebViewConfiguration()
webViewConfiguration.userContentController = userContentController
webView = WKWebView(frame: .zero, configuration: webViewConfiguration)

在我的情况下,CustomContentControllerWKUserContentController的子类,其中add(_ scriptMessageHandler: WKScriptMessageHandler, name: String)方法被调用,但我不认为这是重要的。

我认为必须先实例化WKUserContentController并将其应用于WKWebViewConfiguration ,然后才能通过WKWebView(frame: .zero, configuration: webViewConfiguration)

初始化 WKWebView

如果已创建WKWebView并然后,则尝试更改WKWebViewConfiguration,您将遇到JSContext中无法使用的window.webkit

答案 3 :(得分:0)

我遇到了同样的问题。浪费了2个小时之后,我发现下面这个工作正常。但我不知道为什么。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    WKUserContentController *userCctrl = [[WKUserContentController alloc] init];
    [userCctrl addScriptMessageHandler:self name:@"jscall"];
    WKWebViewConfiguration *wbConfiger = [[WKWebViewConfiguration alloc] init];
    wbConfiger.userContentController = userCctrl;
    CGSize size = [UIScreen mainScreen].bounds.size;
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, size.width, size.height - 20)  configuration:wbConfiger];
    [self.view addSubview:webView];
    webView.UIDelegate = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [webView evaluateJavaScript:@"if (window.webkit === undefined) { alert('未注册的 window.webkit'); } else { window.webkit.messageHandlers.jscall.postMessage({title:'标题'}); }" completionHandler:^(id obj, NSError *error) {
            NSLog(@"run js completion with error = %@", error);
    }];
    });
}
#pragma mark -
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"run js alert panel message = %@", message);
    completionHandler();
}
#pragma mark -
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"wkwebview run javascript name = %@, body = %@", message.name, message.body);
}

答案 4 :(得分:0)

最后为我提供的解决方案是使用

在 webview 上启用 javascript
webview?.configuration.preferences.javaScriptEnabled = true